File size: 11,530 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
---
title: cookies
description: API Reference for the cookies function.
---
`cookies` is an **async** function that allows you to read the HTTP incoming request cookies in [Server Components](/docs/app/getting-started/server-and-client-components), and read/write outgoing request cookies in [Server Actions](/docs/app/getting-started/updating-data) or [Route Handlers](/docs/app/api-reference/file-conventions/route).
```tsx filename="app/page.tsx" switcher
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
```
```js filename="app/page.js" switcher
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
```
## Reference
### Methods
The following methods are available:
| Method | Return Type | Description |
| --------------------------- | ---------------- | ------------------------------------------------------------------------------- |
| `get('name')` | Object | Accepts a cookie name and returns an object with the name and value. |
| `getAll()` | Array of objects | Returns a list of all the cookies with a matching name. |
| `has('name')` | Boolean | Accepts a cookie name and returns a boolean based on if the cookie exists. |
| `set(name, value, options)` | - | Accepts a cookie name, value, and options and sets the outgoing request cookie. |
| `delete(name)` | - | Accepts a cookie name and deletes the cookie. |
| `clear()` | - | Deletes all cookies. |
| `toString()` | String | Returns a string representation of the cookies. |
### Options
When setting a cookie, the following properties from the `options` object are supported:
| Option | Type | Description |
| ----------------- | -------------------------------------- | ---------------------------------------------------------------------------------- |
| `name` | String | Specifies the name of the cookie. |
| `value` | String | Specifies the value to be stored in the cookie. |
| `expires` | Date | Defines the exact date when the cookie will expire. |
| `maxAge` | Number | Sets the cookie’s lifespan in seconds. |
| `domain` | String | Specifies the domain where the cookie is available. |
| `path` | String, default: `'/'` | Limits the cookie's scope to a specific path within the domain. |
| `secure` | Boolean | Ensures the cookie is sent only over HTTPS connections for added security. |
| `httpOnly` | Boolean | Restricts the cookie to HTTP requests, preventing client-side access. |
| `sameSite` | Boolean, `'lax'`, `'strict'`, `'none'` | Controls the cookie's cross-site request behavior. |
| `priority` | String (`"low"`, `"medium"`, `"high"`) | Specifies the cookie's priority |
| `encode('value')` | Function | Specifies a function that will be used to encode a cookie's value. |
| `partitioned` | Boolean | Indicates whether the cookie is [partitioned](https://github.com/privacycg/CHIPS). |
The only option with a default value is `path`.
To learn more about these options, see the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies).
## Good to know
- `cookies` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access cookies.
- In version 14 and earlier, `cookies` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
- `cookies` is a [Dynamic API](/docs/app/getting-started/partial-prerendering#dynamic-rendering) whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering).
- The `.delete` method can only be called:
- In a [Server Action](/docs/app/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route).
- If it belongs to the same domain from which `.set` is called. For wildcard domains, the specific subdomain must be an exact match. 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/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route).
## 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
You can use the `(await cookies()).get('name')` method to get a single cookie:
```tsx filename="app/page.tsx" switcher
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
```
```jsx filename="app/page.js" switcher
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
```
### Getting all cookies
You can use the `(await cookies()).getAll()` method to get all cookies with a matching name. If `name` is unspecified, it returns all the available cookies.
```tsx filename="app/page.tsx" switcher
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
return cookieStore.getAll().map((cookie) => (
<div key={cookie.name}>
<p>Name: {cookie.name}</p>
<p>Value: {cookie.value}</p>
</div>
))
}
```
```jsx filename="app/page.js" switcher
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
return cookieStore.getAll().map((cookie) => (
<div key={cookie.name}>
<p>Name: {cookie.name}</p>
<p>Value: {cookie.value}</p>
</div>
))
}
```
### Setting a cookie
You can use the `(await cookies()).set(name, value, options)` method in a [Server Action](/docs/app/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route) to set a cookie. The [`options` object](#options) is optional.
```tsx filename="app/actions.ts" switcher
'use server'
import { cookies } from 'next/headers'
export async function create(data) {
const cookieStore = await cookies()
cookieStore.set('name', 'lee')
// or
cookieStore.set('name', 'lee', { secure: true })
// or
cookieStore.set({
name: 'name',
value: 'lee',
httpOnly: true,
path: '/',
})
}
```
```js filename="app/actions.js" switcher
'use server'
import { cookies } from 'next/headers'
export async function create(data) {
const cookieStore = await cookies()
cookieStore.set('name', 'lee')
// or
cookieStore.set('name', 'lee', { secure: true })
// or
cookieStore.set({
name: 'name',
value: 'lee',
httpOnly: true,
path: '/',
})
}
```
### Checking if a cookie exists
You can use the `(await cookies()).has(name)` method to check if a cookie exists:
```tsx filename="app/page.ts" switcher
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const hasCookie = cookieStore.has('theme')
return '...'
}
```
```jsx filename="app/page.js" switcher
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const hasCookie = cookieStore.has('theme')
return '...'
}
```
### Deleting cookies
There are three ways you can delete a cookie.
Using the `delete()` method:
```tsx filename="app/actions.ts" switcher
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).delete('name')
}
```
```js filename="app/actions.js" switcher
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).delete('name')
}
```
Setting a new cookie with the same name and an empty value:
```tsx filename="app/actions.ts" switcher
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', '')
}
```
```js filename="app/actions.js" switcher
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', '')
}
```
Setting the `maxAge` to 0 will immediately expire a cookie. `maxAge` accepts a value in seconds.
```tsx filename="app/actions.ts" switcher
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', 'value', { maxAge: 0 })
}
```
```js filename="app/actions.js" switcher
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', 'value', { maxAge: 0 })
``
}
```
## Version History
| Version | Changes |
| ------------ | ------------------------------------------------------------------------------------------------------ |
| `v15.0.0-RC` | `cookies` is now an async function. A [codemod](/docs/app/guides/upgrading/codemods#150) is available. |
| `v13.0.0` | `cookies` introduced. |
|