2022-10-06 09:15:30 +00:00
---
2023-10-18 10:59:43 +00:00
title: 'useCookie'
2022-10-06 09:15:30 +00:00
description: useCookie is an SSR-friendly composable to read and write cookies.
2023-10-18 10:59:43 +00:00
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/cookie.ts
size: xs
2022-10-06 09:15:30 +00:00
---
2021-11-22 20:43:00 +00:00
2022-10-06 09:15:30 +00:00
Within your pages, components and plugins you can use `useCookie` , an SSR-friendly composable to read and write cookies.
2021-11-22 20:43:00 +00:00
2023-10-18 10:59:43 +00:00
```ts
2021-11-22 20:43:00 +00:00
const cookie = useCookie(name, options)
```
2024-01-31 09:46:21 +00:00
::alert{icon=👉}
`useCookie` only works in the [Nuxt context ](/docs/guide/going-further/nuxt-app#the-nuxt-context ).
::
2023-10-18 10:59:43 +00:00
::callout
2021-11-22 23:24:12 +00:00
`useCookie` ref will automatically serialize and deserialize cookie value to JSON.
2021-11-22 20:43:00 +00:00
::
## Example
2021-11-22 23:24:12 +00:00
The example below creates a cookie called `counter` . If the cookie doesn't exist, it is initially set to a random value. Whenever we update the `counter` variable, the cookie will be updated accordingly.
2021-11-22 20:43:00 +00:00
2023-10-18 10:59:43 +00:00
```vue [app.vue]
2023-07-18 10:31:45 +00:00
< script setup lang = "ts" >
const counter = useCookie('counter')
2023-10-18 10:59:43 +00:00
2023-07-18 10:31:45 +00:00
counter.value = counter.value || Math.round(Math.random() * 1000)
< / script >
2021-11-22 20:43:00 +00:00
< template >
< div >
2022-12-19 11:50:46 +00:00
< h1 > Counter: {{ counter || '-' }}< / h1 >
< button @click =" counter = null" > reset</ button >
< button @click =" counter-- " > -</ button >
< button @click =" counter ++" > +</ button >
2021-11-22 20:43:00 +00:00
< / div >
< / template >
```
2023-10-18 10:59:43 +00:00
:link-example{to="/docs/examples/advanced/use-cookie"}
2021-11-22 20:43:00 +00:00
## Options
2021-11-22 23:24:12 +00:00
Cookie composable accepts several options which let you modify the behavior of cookies.
2021-11-22 20:43:00 +00:00
2021-11-22 23:24:12 +00:00
Most of the options will be directly passed to the [cookie ](https://github.com/jshttp/cookie ) package.
2021-11-22 20:43:00 +00:00
### `maxAge` / `expires`
2023-10-18 10:59:43 +00:00
Use these options to set the expiration of the cookie.
`maxAge` : Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute ](https://tools.ietf.org/html/rfc6265#section-5.2.2 ).
2021-11-22 20:43:00 +00:00
The given number will be converted to an integer by rounding down. By default, no maximum age is set.
2023-10-18 10:59:43 +00:00
`expires` : Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute ](https://tools.ietf.org/html/rfc6265#section-5.2.1 ).
2021-11-22 23:24:12 +00:00
By default, no expiration is set. Most clients will consider this a "non-persistent cookie" and
2021-11-22 20:43:00 +00:00
will delete it on a condition like exiting a web browser application.
2023-10-18 10:59:43 +00:00
::callout
The [cookie storage model specification ](https://tools.ietf.org/html/rfc6265#section-5.3 ) states that if both `expires` and
2021-11-22 23:24:12 +00:00
`maxAge` is set, then `maxAge` takes precedence, but not all clients may obey this,
so if both are set, they should point to the same date and time!
2021-11-22 20:43:00 +00:00
::
2023-10-18 10:59:43 +00:00
::callout
2021-11-22 23:24:12 +00:00
If neither of `expires` and `maxAge` is set, the cookie will be session-only and removed when the user closes their browser.
2021-11-22 20:43:00 +00:00
::
2021-11-24 15:24:50 +00:00
### `httpOnly`
2021-11-22 20:43:00 +00:00
Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute ](https://tools.ietf.org/html/rfc6265#section-5.2.6 ). When truthy,
2021-11-22 23:24:12 +00:00
the `HttpOnly` attribute is set; otherwise it is not. By default, the `HttpOnly` attribute is not set.
2021-11-22 20:43:00 +00:00
2023-10-18 10:59:43 +00:00
::callout
Be careful when setting this to `true` , as compliant clients will not allow client-side
2021-11-22 20:43:00 +00:00
JavaScript to see the cookie in `document.cookie` .
::
2021-11-24 15:24:50 +00:00
### `secure`
2021-11-22 20:43:00 +00:00
Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute ](https://tools.ietf.org/html/rfc6265#section-5.2.5 ). When truthy,
2021-11-22 23:24:12 +00:00
the `Secure` attribute is set; otherwise it is not. By default, the `Secure` attribute is not set.
2021-11-22 20:43:00 +00:00
2023-10-18 10:59:43 +00:00
::callout
Be careful when setting this to `true` , as compliant clients will not send the cookie back to
2021-11-22 20:43:00 +00:00
the server in the future if the browser does not have an HTTPS connection. This can lead to hydration errors.
::
2021-11-24 15:24:50 +00:00
### `domain`
2021-11-22 20:43:00 +00:00
2023-10-18 10:59:43 +00:00
Specifies the value for the [`Domain` `Set-Cookie` attribute ](https://tools.ietf.org/html/rfc6265#section-5.2.3 ). By default, no domain is set, and most clients will consider applying the cookie only to the current domain.
2021-11-22 20:43:00 +00:00
2021-11-24 15:24:50 +00:00
### `path`
2021-11-22 20:43:00 +00:00
2023-10-18 10:59:43 +00:00
Specifies the value for the [`Path` `Set-Cookie` attribute ](https://tools.ietf.org/html/rfc6265#section-5.2.4 ). By default, the path is considered the ["default path" ](https://tools.ietf.org/html/rfc6265#section-5.1.4 ).
2021-11-22 20:43:00 +00:00
2021-11-24 15:24:50 +00:00
### `sameSite`
2021-11-22 20:43:00 +00:00
2021-11-22 23:24:12 +00:00
Specifies the `boolean` or `string` value for the [`SameSite` `Set-Cookie` attribute ](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 ).
2021-11-22 20:43:00 +00:00
2021-11-22 23:24:12 +00:00
- `true` will set the `SameSite` attribute to `Strict` for strict same-site enforcement.
2021-11-22 20:43:00 +00:00
- `false` will not set the `SameSite` attribute.
2021-11-22 23:24:12 +00:00
- `'lax'` will set the `SameSite` attribute to `Lax` for lax same-site enforcement.
2021-11-22 20:43:00 +00:00
- `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
2021-11-22 23:24:12 +00:00
- `'strict'` will set the `SameSite` attribute to `Strict` for strict same-site enforcement.
2021-11-22 20:43:00 +00:00
More information about the different enforcement levels can be found in [the specification ](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 ).
2021-11-24 15:24:50 +00:00
### `encode`
2021-11-22 20:43:00 +00:00
2021-11-22 23:24:12 +00:00
Specifies a function that will be used to encode a cookie's value. Since the value of a cookie
2021-11-22 20:43:00 +00:00
has a limited character set (and must be a simple string), this function can be used to encode
a value into a string suited for a cookie's value.
The default encoder is the `JSON.stringify` + `encodeURIComponent` .
2021-11-24 15:24:50 +00:00
### `decode`
2021-11-22 20:43:00 +00:00
Specifies a function that will be used to decode a cookie's value. Since the value of a cookie
has a limited character set (and must be a simple string), this function can be used to decode
2021-11-22 23:24:12 +00:00
a previously encoded cookie value into a JavaScript string or other object.
2021-11-22 20:43:00 +00:00
The default decoder is `decodeURIComponent` + [destr ](https://github.com/unjs/destr ).
2023-10-18 10:59:43 +00:00
::callout
If an error is thrown from this function, the original, non-decoded cookie value will
2021-11-22 20:43:00 +00:00
be returned as the cookie's value.
::
2022-04-13 17:41:41 +00:00
### `default`
Specifies a function that returns the cookie's default value. The function can also return a `Ref` .
2023-11-28 13:35:43 +00:00
### `readonly`
Allows _accessing_ a cookie value without the ability to set it.
2022-12-19 11:50:46 +00:00
### `watch`
Specifies the `boolean` or `string` value for [watch ](https://vuejs.org/api/reactivity-core.html#watch ) cookie ref data.
2023-10-18 10:59:43 +00:00
- `true` - Will watch cookie ref data changes and its nested properties (default).
2022-12-19 11:50:46 +00:00
- `shallow` - Will watch cookie ref data changes for only top level properties
2023-10-18 10:59:43 +00:00
- `false` - Will not watch cookie ref data changes.
2022-12-19 11:50:46 +00:00
**Example 1:**
```vue
2023-07-18 10:31:45 +00:00
< script setup lang = "ts" >
2022-12-19 11:50:46 +00:00
const user = useCookie(
'userInfo',
{
default: () => ({ score: -1 }),
watch: false
}
)
if (user.value & & user.value !== null) {
user.value.score++; // userInfo cookie not update with this change
}
< / script >
2023-07-18 10:31:45 +00:00
< template >
< div > User score: {{ user?.score }}< / div >
< / template >
2022-12-19 11:50:46 +00:00
```
**Example 2:**
```vue
2023-07-18 10:31:45 +00:00
< script setup lang = "ts" >
2022-12-19 11:50:46 +00:00
const list = useCookie(
'list',
{
default: () => [],
watch: 'shallow'
}
)
function add() {
list.value?.push(Math.round(Math.random() * 1000))
// list cookie not update with this change
}
function save() {
if (list.value & & list.value !== null) {
list.value = [...list.value]
// list cookie update with this change
}
}
< / script >
2023-07-18 10:31:45 +00:00
< template >
< div >
< h1 > List< / h1 >
< pre > {{ list }}< / pre >
< button @click =" add " > Add</ button >
< button @click =" save " > Save</ button >
< / div >
< / template >
2022-12-19 11:50:46 +00:00
```
2023-10-18 10:59:43 +00:00
## Cookies in API Routes
2021-11-22 20:43:00 +00:00
2022-08-22 08:49:27 +00:00
You can use `getCookie` and `setCookie` from [`h3` ](https://github.com/unjs/h3 ) package to set cookies in server API routes.
2021-11-22 20:43:00 +00:00
2023-10-18 10:59:43 +00:00
```ts [server/api/counter.ts]
2022-06-10 13:58:10 +00:00
export default defineEventHandler(event => {
2021-11-22 23:24:12 +00:00
// Read counter cookie
2022-08-22 08:49:27 +00:00
let counter = getCookie(event, 'counter') || 0
2021-11-22 20:43:00 +00:00
2021-11-22 23:24:12 +00:00
// Increase counter cookie by 1
2022-06-10 13:58:10 +00:00
setCookie(event, 'counter', ++counter)
2021-11-22 20:43:00 +00:00
2021-11-22 23:24:12 +00:00
// Send JSON response
return { counter }
2022-06-10 13:58:10 +00:00
})
2021-11-22 20:43:00 +00:00
```
2022-04-09 09:25:13 +00:00
2023-10-18 10:59:43 +00:00
:link-example{to="/docs/examples/advanced/use-cookie"}