Next.js Discord

Discord Forum

Trouble Setting Cookies in Next.js API Route Using Response Headers

Answered
Pixiebob posted this in #help-forum
Open in Discord
PixiebobOP
Hello community,

I'm currently working on a Next.js project, and I'm facing an issue with setting cookies in an API route. I've tried to set a cookie in the response headers, but it doesn't seem to be working as expected when I tried to get the cookies .

Here's a simplified version of my code:

```javascript
export const dynamic = "force-static";
import { NextRequest } from "next/server";

export async function GET(request: NextRequest) {
const theme = request.cookies.get("theme");

console.log("Current theme:", theme); ==> undefined

// Set the "theme" cookie in the response headers
const response = new Response("Hello, Next.js!", {
status: 200,
headers: {
"Set-Cookie": "theme=dark; Path=/", // Adjust the options as needed
},
});

// Log the updated theme value
console.log("Updated theme:", request.cookies.get("theme")); ==> undefined

// Return the response
return response;
}
Answered by not-milo.tsx
There's no way around it. If you want access to dynamic values like headers and cookies in a route handler you can't use a static export. A static export is just that, static.

See: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#route-handlers
View full answer

5 Replies

The cookie is set by your browser upon receiving the response. You can't expect the request to immediately update like that.

Also, why are you forcing your api route to be static? This will make it so that cookies() and headers() return empty values.
Cookies are set once it reaches your browser.
request.cookies.get() would simply getting the cookies from the previous value...
There's no way around it. If you want access to dynamic values like headers and cookies in a route handler you can't use a static export. A static export is just that, static.

See: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#route-handlers
Answer