Usage
Within your pages, components, and plugins, you can useuseCookie to read and write cookies in an SSR-friendly way.
useCookie only works in the Nuxt context.Parameters
The name of the cookie.
Options to control cookie behavior.
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.
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.
Function returning the default value if the cookie does not exist. The function can also return a
Ref.Whether to watch for changes and update the cookie.
true for deep watch, 'shallow' for shallow watch (only top-level properties), false to disable.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.If
true, disables writing to the cookie.Max age in seconds for the cookie. The given number will be converted to an integer by rounding down.
Expiration date for the cookie. By default, no expiration is set.
Sets the HttpOnly attribute. When true, compliant clients will not allow client-side JavaScript to see the cookie in
document.cookie.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.
Sets the Partitioned attribute. This is an attribute that has not yet been fully standardized.
Sets the Domain attribute. By default, no domain is set, and most clients will consider applying the cookie only to the current domain.
Sets the Path attribute.
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 calledcounter. 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 usegetCookie and setCookie from h3 package to set cookies in server API routes.
[server/api/counter.ts]