Next.js Discord

Discord Forum

How do I redirect but also set a cookie inside a route handler?

Unanswered
Large Münsterländer posted this in #help-forum
Open in Discord
Large MünsterländerOP
Title says all

4 Replies

Why not just set the cookie in the handler and then redirect by checking the response in the page where you are fetching.
// Route handler
function GET () {
    // Return set cookie
}

// Page
function page() {
    const res = fetch(...)
    if (res.ok()) {
        router.redirect(..)
    }
}
@Large Münsterländer bc the route is a callback for an auth
try
const res = NextResponse.redirect(new URL("/", req.url));
res.cookies.set("cookie", "value");
return res;