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: