Next.js Discord

Discord Forum

NextJS doesn't respect Host header or X-Forwaded-Host

Unanswered
Tomistoma posted this in #help-forum
Open in Discord
Avatar
TomistomaOP
Hi, how can you get NextJS based apps to use the Host header when doing redirects or X-Forwarded-Host ?

We're trying to use the value from req.nextUrl.host but it seems to be off.

16 Replies

Avatar
is this in middleware or Route Handlers?
Avatar
TomistomaOP
@Plague both seems to be working just the same 🏧
Avatar
Have you tried using the headers() function from next/server instead of the request object directly?
Avatar
TomistomaOP
No, but ise there a reason on why the request.nextUrl.host shouldn't work ? 🤔
Avatar
Not sure, but the documentation doesn't state anything about nextUrl.host, where it specfically states that headers() can read x-forwarded-host
Avatar
TomistomaOP
Hmm, ok yeah then that probably sounds like the better thing imho
Avatar
Yeah it's how you should always read headers in Next.js
Avatar
TomistomaOP
@Plague Should redirect() work or ? It's also forwarding to the wrong place
Avatar
The redirect function will work for redirecting users from any server environment that isn't a Route Handler or Middleware, so Server Component/Actions
Redirecting out of middleware/Route Handler should be handled by the NextResponse.redirect() helper
or just Response.redirect() in Route Handlers, either one works, but NextResponse.redirect() I believe is needed for middleware.
Avatar
TomistomaOP
It's already using NextResponse.redirect() in teh code as far as I can see
Avatar
There are like seven redirects in here, which one is redirecting to the wrong place?
Avatar
TomistomaOP
I guess all of them would exibit the same behaviour ?
Avatar
TomistomaOP
@Plague Hence why I wondered why doesn't Next then actually use the Host header