Unverified Commit 8a69b959 authored by Matt Mayfield's avatar Matt Mayfield Committed by GitHub

🍪 Understanding Cookie Behavior in Server Components (#73001)

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: 's avatarDelba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
parent 3f4899f7
......@@ -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
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment