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