#How can I set a cookie when a page loads in a React Server Component?
1 messages · Page 1 of 1 (latest)
Hi @solid mango. 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 set cookies in Server Actions, Route Handlers, or Middleware using the cookies().set(name, value, options) function. However, HTTP does not allow setting cookies after streaming starts, so you cannot set cookies from a page or layout directly.
Here is an example of how you can set a cookie in a Server Action:
'use server'
import { cookies } from 'next/headers'
async function create(data) {
cookies().set('name', 'lee')
// or
cookies().set('name', 'lee', { secure: true })
// or
cookies().set({
name: 'name',
value: 'lee',
httpOnly: true,
path: '/',
})
}
(Source: Next.js Documentation (https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options))
If you need to set a cookie in middleware, you can use a workaround as discussed in this Github issue (https://github.com/vercel/next.js/issues/49442). This workaround involves copying cookies from the Set-Cookie header of the response to the Cookie header of the request, so that it will appear to SSR/RSC as if the user already has the new cookies.