From 8a69b959680414172ae908e88b3beb413100bc77 Mon Sep 17 00:00:00 2001 From: Matt Mayfield Date: Thu, 21 Nov 2024 10:49:05 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=8D=AA=20Understanding=20Cookie=20Behavio?= =?UTF-8?q?r=20in=20Server=20Components=20(#73001)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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> --- docs/01-app/03-api-reference/04-functions/cookies.mdx | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/01-app/03-api-reference/04-functions/cookies.mdx b/docs/01-app/03-api-reference/04-functions/cookies.mdx index f94d1caf7f730..ae3deffa1fb40 100644 --- a/docs/01-app/03-api-reference/04-functions/cookies.mdx +++ b/docs/01-app/03-api-reference/04-functions/cookies.mdx @@ -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