Skip to content

Commit

Permalink
🍪 Understanding Cookie Behavior in Server Components (#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 <32464864+delbaoliveira@users.noreply.github.com>
  • Loading branch information
2 people authored and wyattjoh committed Nov 28, 2024
1 parent 75d6917 commit 80b5fff
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 80b5fff

Please sign in to comment.