Next.js API Proxy with rewrites for Microservices
Problem
One Next.js frontend, multiple backend microservices on different ports. Calling them directly from the client means dealing with CORS configuration for every service.
Solution
// next.config.js
const nextConfig = {
async rewrites() {
return [
{
source: '/api/proxy/token/:path*',
destination: 'http://127.0.0.1:3001/:path*',
},
{
source: '/api/proxy/file/:path*',
destination: 'http://127.0.0.1:3002/:path*',
},
];
},
};
module.exports = nextConfig;
The client calls /api/proxy/token/verify and Next.js proxies it server-side to http://127.0.0.1:3001/verify.
Key Points
rewriteschanges the destination without changing the URL visible to the client. Unlikeredirects, the proxy is transparent.:path*is a wildcard that forwards all sub-paths./api/proxy/token/a/b/cmaps tohttp://127.0.0.1:3001/a/b/c.- Since requests originate from the same domain, no CORS configuration is needed. Especially convenient during development.