Next.js Discord

Discord Forum

How to set cookies from an API call?

Unanswered
dannyk08 posted this in #help-forum
Open in Discord
Hello everyone

I'm coming across an issue trying to set cookies on the client from an API call. I've narrowed it down to the basics and it doesn't work.

Take this example
.ts
export async function GET() {
  const cookie = {
    name: 'my-cookie',
    value: 'this is my cookie value',
    maxAge: 3600,
    httpOnly: true,
  }

  const response = NextResponse.json({
    data: {
      some: 'data',
    },
  })

  response.cookies.set(cookie)

  return response
}


I'd expect a cookie to be set on the client but this is not happening.
Please advice on what the correct approach is.

1 Reply

NOTE: I've also tried this approach and cookies are not being set

https://nextjs.org/docs/app/building-your-application/routing/router-handlers#dynamic-functions