Skip to main content

Usage

Within your pages, components, and plugins, you can use useCookie to read and write cookies in an SSR-friendly way.
useCookie only works in the Nuxt context.
The returned ref will automatically serialize and deserialize cookie values to JSON.

Parameters

string
required
The name of the cookie.
CookieOptions<T>
Options to control cookie behavior.
(value: string) => T
Custom function to decode the cookie value. Since the value of a cookie has a limited character set, this function can be used to decode a previously encoded cookie value into a JavaScript string or other object.
(value: T) => string
Custom function to encode the cookie value. Since the value of a cookie has a limited character set, this function can be used to encode a value into a string suited for a cookie’s value.
() => T | Ref<T>
Function returning the default value if the cookie does not exist. The function can also return a Ref.
boolean | 'shallow'
default:"true"
Whether to watch for changes and update the cookie. true for deep watch, 'shallow' for shallow watch (only top-level properties), false to disable.
boolean
default:"false"
If true, the cookie expiration will be refreshed on every explicit write (e.g. cookie.value = cookie.value), even if the value itself hasn’t changed.
boolean
default:"false"
If true, disables writing to the cookie.
number
Max age in seconds for the cookie. The given number will be converted to an integer by rounding down.
Date
Expiration date for the cookie. By default, no expiration is set.
boolean
default:"false"
Sets the HttpOnly attribute. When true, compliant clients will not allow client-side JavaScript to see the cookie in document.cookie.
boolean
default:"false"
Sets the Secure attribute. When true, compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.
boolean
default:"false"
Sets the Partitioned attribute. This is an attribute that has not yet been fully standardized.
string
Sets the Domain attribute. By default, no domain is set, and most clients will consider applying the cookie only to the current domain.
string
default:"'/'"
Sets the Path attribute.
boolean | 'lax' | 'strict' | 'none'
Sets the SameSite attribute. true sets to Strict, false does not set the attribute, or use 'lax', 'strict', or 'none'.

Return Values

A Vue Ref representing the cookie value. Updating the ref will update the cookie (unless readonly is set). The ref is SSR-friendly and will work on both client and server.

Examples

Basic Usage

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.
[app/app.vue]

Readonly Cookies

Writable Cookies

Refreshing Cookies

Cookies in API Routes

You can use getCookie and setCookie from h3 package to set cookies in server API routes.
[server/api/counter.ts]

Type