Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Last active December 22, 2023 02:25
Show Gist options
  • Save wobsoriano/0f3f22e41e0dc951d29530a32d15d5dd to your computer and use it in GitHub Desktop.
Save wobsoriano/0f3f22e41e0dc951d29530a32d15d5dd to your computer and use it in GitHub Desktop.
Nuxt 3 http-proxy-middleware
// ~/server/middleware/proxy.ts
import { defineEventHandler } from 'h3'
import { createProxyMiddleware } from 'http-proxy-middleware'; // npm install http-proxy-middleware@beta
const apiProxyMiddleware = createProxyMiddleware({
target: 'https://jsonplaceholder.typicode.com',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api/todos': '/todos',
'^/api/users': '/users'
},
pathFilter: [
'/api/todos',
'/api/users'
],
logger: console
})
export default defineEventHandler(async (event) => {
await new Promise((resolve, reject) => {
const next = (err?: unknown) => {
if (err) {
reject(err)
} else {
resolve(true)
}
}
apiProxyMiddleware(event.req, event.res, next)
})
})
@maxtomczyk
Copy link

Amazing starting point for my needs, thanks <3

@wobsoriano
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment