Next.js Discord

Discord Forum

Proxy for API requests

Answered
Philippine Crocodile posted this in #help-forum
Open in Discord
Philippine CrocodileOP
Hi! I want to proxy API requests from /api/* to https://api.domain.com/*. So this one will remove CORS problem and give me more security by making requests to the same domain. What's the best way (and especially performant way) to achive this? I considered to use next.config.js and rewrites, but this one make a redirect with status code instead of actually silently proxying the request. Am I understood right how does it work? I use nextjs version 14 and deploy to Vercel. So, I would happy to hear any solution that will be peformant as much as possible
Answered by Asiatic Lion
next config rewrites works as a proxy without redirects: https://nextjs.org/docs/app/api-reference/next-config-js/rewrites#:~:text=Rewrites%20act%20as%20a%20URL%20proxy%20and%20mask%20the%20destination%20path%2C%20making%20it%20appear%20the%20user%20hasn%27t%20changed%20their%20location%20on%20the%20site

If you are seeing redirects while using rewrites config I'd suspect the redirect response is produced in a different layer. Maybe your proxy target being confused by host header or http/https protocol.
View full answer

3 Replies

Philippine CrocodileOP
Also, I found the article where author recommends to use nginx or any other reverse proxy in production instead of rewrites https://damda.dev/articles/80-proxying-requests-in-next-js-simplify-api-calls-and-enhance-security-with-rewrites.html. So this gives me concern that Next.js rewrites are not applicable for production usage, any thoughts?
Asiatic Lion
next config rewrites works as a proxy without redirects: https://nextjs.org/docs/app/api-reference/next-config-js/rewrites#:~:text=Rewrites%20act%20as%20a%20URL%20proxy%20and%20mask%20the%20destination%20path%2C%20making%20it%20appear%20the%20user%20hasn%27t%20changed%20their%20location%20on%20the%20site

If you are seeing redirects while using rewrites config I'd suspect the redirect response is produced in a different layer. Maybe your proxy target being confused by host header or http/https protocol.
Answer
Philippine CrocodileOP
omg, I'm so sorry, I confused redirects with rewrites. Thank you so much! I appreciate your time to get me into the right point. Thanks!