Skip to content

Commit

Permalink
🍪 Understanding Cookie Behavior in Server Components (vercel#73001)
Browse files Browse the repository at this point in the history
This is meant to add a bit more clarity of why we can't set cookies to
the browser in a server component even if it's through a server action
or route handler.

Co-authored-by: Delba de Oliveira <[email protected]>
  • Loading branch information
themattmayfield and delbaoliveira authored Nov 21, 2024
1 parent 3f4899f commit 8a69b95
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions docs/01-app/03-api-reference/04-functions/cookies.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ To learn more about these options, see the [MDN docs](https://developer.mozilla.
- If it belongs to the same domain from which `.set` is called. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete.
- HTTP does not allow setting cookies after streaming starts, so you must use `.set` in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers).

## Understanding Cookie Behavior in Server Components

When working with cookies in Server Components, it's important to understand that cookies are fundamentally a client-side storage mechanism:

- **Reading cookies** works in Server Components because you're accessing the cookie data that the client's browser sends to the server in the HTTP request headers.
- **Setting cookies** cannot be done directly in a Server Component, even when using a Route Handler or Server Action. This is because cookies are actually stored by the browser, not the server.

The server can only send instructions (via `Set-Cookie` headers) to tell the browser to store cookies - the actual storage happens on the client side. This is why cookie operations that modify state (`.set`, `.delete`, `.clear`) must be performed in a Route Handler or Server Action where the response headers can be properly set.

## Examples

### Getting a cookie
Expand Down

0 comments on commit 8a69b95

Please sign in to comment.