new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Nuxt · API · all subjects

composables/usecookie

23 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

useCookie composable signature and return type

The useCookie composable has the signature: useCookie<T = string | null | undefined>(name: string, options?: CookieOptions<T>): CookieRef<T>. It takes a cookie name as a string and optional CookieOptions object, returning a CookieRef<T> which extends Vue Ref<T>. The returned ref automatically serializes and deserializes cookie values to JSON.

CookieOptions interface definition

CookieOptions<T> extends Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'> and has these properties: decode (function (value: string) => T with default decodeURIComponent + destr), encode (function (value: T) => string with default JSON.stringify + encodeURIComponent), default (() => T | Ref<T>, default undefined), watch (boolean | 'shallow', default true), readonly (boolean, default false), refresh (boolean, default false, v4.4+), maxAge (number, default undefined), expires (Date | (() => Date | undefined), default undefined), httpOnly (boolean, default false), secure (boolean, default false), partitioned (boolean, default false), domain (string, default undefined), path (string, default '/'), sameSite (boolean | string, default undefined).

useCookie decode option behavior

The decode option is a custom function with signature (value: string) => T that decodes the cookie value. The default is decodeURIComponent combined with destr library. If an error is thrown from the decode function, the original non-decoded cookie value will be returned as the cookie's value.

useCookie encode option behavior

The encode option is a custom function with signature (value: T) => string that encodes the cookie value. The default is JSON.stringify combined with encodeURIComponent. Since cookie values have limited character sets and must be simple strings, this function encodes a value into a string suited for a cookie's value.

useCookie default option behavior

The default option is a function with signature () => T | Ref<T> that returns the default value if the cookie does not exist. The function can return either a value of type T or a Vue Ref<T>. The default value is undefined.

useCookie watch option values and behavior

The watch option accepts boolean or 'shallow' string, with default value true. When true, it enables deep watch for changes and updates the cookie. When set to 'shallow', it watches only top level properties. When false, watching is disabled. Note: useCookie values must be manually refreshed when a cookie has changed using refreshCookie utility.

useCookie refresh option behavior

The refresh option (available in v4.4+) is a boolean with default false. When 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. The expiration is not refreshed automatically; you must assign to .value to trigger it.

useCookie readonly option behavior

The readonly option is a boolean with default false. When true, it disables writing to the cookie on both server and client. A default value is still returned by the composable but is never persisted to the browser.

useCookie maxAge option behavior

The maxAge option is a number with default undefined. It specifies the max age in seconds for the cookie, setting the Max-Age Set-Cookie attribute. The given number will be converted to an integer by rounding down. By default, no maximum age is set.

useCookie expires option behavior

The expires option accepts Date | (() => Date | undefined) with default undefined. It sets the expiration date for the cookie, or provides a getter that returns one. When a function is provided, it is evaluated on every cookie write so expiration can be refreshed. Returning undefined creates a session cookie. The getter should be pure with no side effects. If neither expires nor maxAge is set, the cookie is session-only and removed when the user closes their browser. If both are set, maxAge takes precedence per cookie specification, though not all clients may obey this.

useCookie httpOnly option behavior

The httpOnly option is a boolean with default false. It sets the HttpOnly attribute on the cookie. Be careful when setting this to true, as compliant clients will not allow client-side JavaScript to see the cookie in document.cookie.

useCookie secure option behavior

The secure option is a boolean with default false. It sets the Secure Set-Cookie attribute. Be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection, which can lead to hydration errors.

useCookie partitioned option behavior

The partitioned option is a boolean with default false. It sets the Partitioned Set-Cookie attribute. This attribute has not yet been fully standardized and may change in the future. Many clients may ignore this attribute until they understand it. More information is available in the CHIPS proposal.

useCookie domain option behavior

The domain option is a string with default undefined. It sets the Domain Set-Cookie attribute. By default, no domain is set, and most clients will consider applying the cookie only to the current domain.

useCookie path option behavior

The path option is a string with default '/'. It sets the Path Set-Cookie attribute. By default, the path is considered the default path as defined in RFC 6265.

useCookie sameSite option values and behavior

The sameSite option accepts boolean | string with default undefined. It sets the SameSite Set-Cookie attribute. When true, sets SameSite to Strict for strict same-site enforcement. When false, does not set SameSite. String values: 'lax' sets to Lax for lax enforcement, 'none' sets to None for explicit cross-site cookies, 'strict' sets to Strict for strict enforcement.

useCookie works only in Nuxt context

useCookie only works within the Nuxt context. It is available in pages, components, and plugins.

useCookie basic usage example

Example showing basic useCookie usage: ```vue <script setup lang="ts"> const counter = useCookie('counter') counter.value ||= Math.round(Math.random() * 1000) </script> <template> <div> <h1>Counter: {{ counter || '-' }}</h1> <button @click="counter = null"> reset </button> <button @click="counter--"> - </button> <button @click="counter++"> + </button> </div> </template> ``` This example creates a cookie called counter that is initially set to a random value if it doesn't exist. Updating the counter variable updates the cookie accordingly.

useCookie readonly cookies example

Example showing readonly cookies with useCookie: ```vue <script setup lang="ts"> const user = useCookie( 'userInfo', { default: () => ({ score: -1 }), watch: false, }, ) if (user.value) { // the actual `userInfo` cookie will not be updated user.value.score++ } </script> <template> <div>User score: {{ user?.score }}</div> </template> ``` This example shows how to use watch: false to prevent changes from being persisted to the cookie.

useCookie shallow watch example

Example showing shallow watch with useCookie: ```vue <script setup lang="ts"> const list = useCookie( 'list', { default: () => [], watch: 'shallow', }, ) function add () { list.value?.push(Math.round(Math.random() * 1000)) // list cookie won't be updated with this change } function save () { // the actual `list` cookie will be updated list.value &&= [...list.value] } </script> <template> <div> <h1>List</h1> <pre>{{ list }}</pre> <button @click="add"> Add </button> <button @click="save"> Save </button> </div> </template> ``` This example demonstrates that with watch: 'shallow', nested property changes don't update the cookie; you must reassign the value to trigger an update.

useCookie refresh option example

Example showing refresh option with useCookie: ```vue <script setup lang="ts"> const session = useCookie( 'session', { maxAge: 60 * 60, // 1 hour refresh: true, default: () => 'active', }) // Even if the value does not change, // the cookie expiration will be refreshed // every time the setter is called session.value = 'active' </script> <template> <div>Session: {{ session }}</div> </template> ``` This example shows how refresh: true ensures the cookie expiration is refreshed every time the setter is called, even if the value hasn't changed.

useCookie dynamic expiration with getter example

Example showing dynamic expiration with a getter function: ```vue <script setup lang="ts"> const token = useCookie('token', { // Re-evaluated on every write — keep this getter pure expires: () => new Date(Date.now() + 60 * 60 * 1000), // 1 hour from now }) // Assigning a new value also refreshes the cookie expiration token.value = 'new-token' </script> ``` This example demonstrates using a function for the expires option to provide a fresh expiration date every time the cookie is written, useful for sliding sessions or tokens.

useCookie in API routes with getCookie and setCookie

Example showing how to use getCookie and setCookie from h3 package in server API routes: ```ts export default defineEventHandler((event) => { // Read counter cookie let counter = getCookie(event, 'counter') || 0 // Increase counter cookie by 1 setCookie(event, 'counter', ++counter) // Send JSON response return { counter } }) ``` This example demonstrates reading and setting cookies in server API routes using h3's getCookie and setCookie functions instead of the useCookie composable.

Give your agent this brain