Menu

Why does NextResponse.redirect send users to localhost behind nginx?
📰

Why does NextResponse.redirect send users to localhost behind nginx?

DEV Community: nextjs·Great Work·2 days ago
#vQSvGTy4
#devtonextjs#devto#dev#host#next
Reading 0:00
15s threshold

Originally published at runheed.com .

Under next start, a route handler's request.url is built from the address Next itself listens on, not from the Host header your proxy forwards. It does take the scheme from X-Forwarded-Proto, so behind nginx it reads https://localhost:3000/ ... and any redirect built with new URL(path, request.url) sends the user there. Build absolute URLs from a public origin you configure, send a relative Location header, or read the forwarded host when you trust the proxy that sets it.

What happens

We hit this in our own app: a form handler redirected with NextResponse.redirect(new URL(path, request.url)), and in production the browser landed on https://localhost:3030 . nginx was passing the right Host header. We reproduced it in a fresh Next.js 16.4.5 app under next build and next start, with this route:

app/u/route.ts

import { NextRequest , NextResponse } from 'next/server' ;

export function GET ( req : NextRequest ) { return Response . json ( { url : req . url , host : req .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.