#How to Redirect to an External URL with Headers in Next.js 14+

1 messages · Page 1 of 1 (latest)

pine dagger
#

I'm working with Next.js 14+ and need to redirect a user from my Next.js server to an external URL. The catch is that I need to set a custom header and set cookies before performing the redirect.

I used the following code in the server but this doesn't work

res.setHeader('secret-header', 'some secret')
res.redirect(307, 'https://example.com')
res.writeHead(307, {Location: 'https://example.com'})
res.end()
reef stagBOT
#

Hi @pine dagger. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, you can use the redirect function to redirect to an external URL. However, setting custom headers during a redirect can be tricky because when a redirect is sent back to the client, the browser follows the redirect Location header but doesn't include any other headers it receives from the server source (https://github.com/vercel/next.js/issues/65702).

Here's an example of how you can use the redirect function:

import { redirect } from 'next/navigation'
 
export async function GET(request: Request) {
  redirect('<https://nextjs.org/'>)
}

source (https://nextjs.org/docs/app/building-your-application/routing/route-handlers#redirects)

As for setting cookies, Next.js introduced the cookies function in version 13.0.0. You can use this function to set cookies on the server side. Here's an example:

export async function POST() {
  cookies().set("anonymousId", `anonymousId_${crypto.randomUUID()}`)
  return NextResponse.json({ status: 200 })
}

source (https://github.com/vercel/next.js/issues/62800)

However, please note that the headers and cookies set on the server side may not be included when the browser follows the redirect. This is a default behavior of the browser and not a Next.js error source (https://github.com/vercel/next.js/issues/65702).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@pine dagger kapa.ai is still learning and improving, please let us know how it did by reacting below

pine dagger
#

This code you mentioned didn't work. I ended up in an error that says "error: NEXT_REDIRECT".

redirect(' <https : //nextjs.org/'>)