Proxy api requests w/o a custom server #14057
-
Official code example uses a custom server, however by using a custom server, we will lose important performance optimizations, like serverless functions and Automatic Static Optimization. This is NOT acceptable to me. |
Beta Was this translation helpful? Give feedback.
Replies: 8 comments 18 replies
-
did you find a solution for this? |
Beta Was this translation helpful? Give feedback.
-
So I went ahead and found a way to proxy api requests to another server with nextjs builtin "Catch all API routes" capability, using a 3rd party library http-proxy-middleware. Here is my import { createProxyMiddleware } from 'http-proxy-middleware';
// Create proxy instance outside of request handler function to avoid unnecessary re-creation
const apiProxy = createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
pathRewrite: { [`^/api/proxy`]: '' },
secure: false,
});
export default function (req, res) {
apiProxy(req, res, (result) => {
if (result instanceof Error) {
throw result;
}
throw new Error(`Request '${req.url}' is not proxied! We should never reach here!`);
});
}; So all api requests starting with |
Beta Was this translation helpful? Give feedback.
-
You can use custom routes for this: rewrites: () => [
{ source: '/api/proxy/:path*', destination: 'http://localhost:5000/:path*' }
] |
Beta Was this translation helpful? Give feedback.
-
I think that the official example which uses a custom server should be rewritten to the catch-all API routes approach outlined here. |
Beta Was this translation helpful? Give feedback.
-
There is now an official feature for this: Rewrites next.config.js module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:5000/:path*' // Proxy to Backend
}
]
}
} |
Beta Was this translation helpful? Give feedback.
-
Thanks for code snippet above. Was able to write proxy api route w/o HPM. Here is my const proxyConfig: any = {
logLevel: process.env.NODE_ENV === "production" ? "silent" : "warn",
target: ENDPOINT_PROXY_API,
pathRewrite: { "^/api/proxy": "" },
changeOrigin: true,
ws: true,
onError(err, req, res: any) {
res.writeHead(302, {
Location: `${ENDPOINT_PROXY_ORIGIN}/exception?message=${err.message}`,
})
res.end()
},
onProxyReq(proxyReq, req: any, res) {
/**
* manually overwrite origin for CORS (changeOrigin might not work)
*/
proxyReq.setHeader("origin", ENDPOINT_PROXY_ORIGIN)
const requestId = greq.headers[HEADER_REQUEST_ID] // passed from fetch (Browser) to keep request id in browser too
const endpoint = req.url
const method = req.method
logger.info(`[${PlatformUtil.getLoggerTag()}] (${requestId}) REQ ${endpoint} ${method}`)
},
onProxyRes(proxyRes, req: any, res) {
const requestId = greq.headers[HEADER_REQUEST_ID] // passed from fetch (Browser) to keep request id in browser too
const endpoint = req.url
const method = req.method
const status = proxyRes.statusCode
logger.info(`[${PlatformUtil.getLoggerTag()}] (${requestId}) RES ${endpoint} ${method} ${status} `)
},
}
const proxied = createProxyMiddleware(proxyConfig)
export const config = {
api: {
// - https://nextjs.org/docs/api-routes/api-middlewares#custom-config
externalResolver: true,
bodyParser: false, // not to use url encoded form like streaming POST request
},
}
export default proxied |
Beta Was this translation helpful? Give feedback.
-
Rewrites doesnt work when it comes down to webscokets. |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
You can use custom routes for this: