fn

useCookie

v0.0.14testeddemo

Reactive cookie binding — creates a ref synced with a cookie through a pluggable CookieStorageLike backend. By default that is the Cookie Store API when the browser supports it (async, with change-event sync across tabs and server Set-Cookie responses) and document.cookie otherwise (synchronous, BroadcastChannel same-tab/cross-tab sync); pass a custom store to run on top of a framework's cookie context (e.g. Nuxt) including during SSR. Setting the state to null deletes the cookie. Cookie attributes (path, domain, maxAge/expires, secure, sameSite, partitioned) apply to every write; secure defaults to the page's secure-context status, and an explicit secure: false selects the document.cookie adapter since the Cookie Store API can only write Secure cookies.

Examples

ts
const { state: theme } = useCookie('theme', 'system');
ts
const { state: session } = await useCookie('session', '', { maxAge: 3600, sameSite: 'strict' });
ts
// Nuxt (h3) integration: bridge the SSR request so the same call works on
// the server (reads the request's Cookie header, writes Set-Cookie response
// headers) and falls back to the built-in browser adapters on the client.
// ~/composables/createNuxtCookieAdapter.ts
import { deleteCookie, getRequestHeader, setCookie } from 'h3';
import { getCookieValue } from '@robonen/platform/browsers';
import type { CookieStorageLike } from '@robonen/vue';

export function createNuxtCookieAdapter(): CookieStorageLike | undefined {
  if (import.meta.client)
    return undefined; // browser: the default adapters take over

  const event = useRequestEvent()!;
  // Set-Cookie does not update the incoming Cookie header, so reads must
  // overlay this request's own writes (same trick Nuxt's useCookie uses)
  const written = new Map<string, string | null>();

  return {
    getItem(name) {
      if (written.has(name))
        return written.get(name)!;

      // identity decode — the composable owns decoding of raw values
      return getCookieValue(getRequestHeader(event, 'cookie') ?? '', name, raw => raw);
    },
    setItem(name, value, attributes) {
      written.set(name, value);
      setCookie(event, name, value, {
        path: attributes.path,
        domain: attributes.domain,
        maxAge: attributes.maxAge,
        expires: typeof attributes.expires === 'number' ? new Date(attributes.expires) : attributes.expires,
        secure: attributes.secure,
        sameSite: attributes.sameSite,
        partitioned: attributes.partitioned,
        encode: raw => raw, // value arrives already encoded
      });
    },
    removeItem(name, attributes) {
      written.set(name, null);
      // deletion must repeat the identity attributes to match the cookie
      deleteCookie(event, name, { path: attributes.path, domain: attributes.domain });
    },
    // no onChange: a server request has no cookie change events
  };
}

// anywhere in the app — works during SSR and in the browser
const { state: locale } = useCookie('locale', 'en', { store: createNuxtCookieAdapter() });

Demo

Loading demo…

Signatures

ts
export function useCookie<T extends string, Shallow extends boolean = true>(name: MaybeRefOrGetter<string>, initialValue: MaybeRefOrGetter<T>, options?: UseCookieOptions<T, Shallow>): UseCookieReturn<T, Shallow>;
ts
export function useCookie<T extends number, Shallow extends boolean = true>(name: MaybeRefOrGetter<string>, initialValue: MaybeRefOrGetter<T>, options?: UseCookieOptions<T, Shallow>): UseCookieReturn<T, Shallow>;
ts
export function useCookie<T extends boolean, Shallow extends boolean = true>(name: MaybeRefOrGetter<string>, initialValue: MaybeRefOrGetter<T>, options?: UseCookieOptions<T, Shallow>): UseCookieReturn<T, Shallow>;
ts
export function useCookie<T, Shallow extends boolean = true>(name: MaybeRefOrGetter<string>, initialValue: MaybeRefOrGetter<T>, options?: UseCookieOptions<T, Shallow>): UseCookieReturn<T, Shallow>;
ts
export function useCookie<T = unknown, Shallow extends boolean = true>(name: MaybeRefOrGetter<string>, initialValue: MaybeRefOrGetter<null>, options?: UseCookieOptions<T, Shallow>): UseCookieReturn<T, Shallow>;

Type Parameters

T
Shallowextends boolean= true

Parameters

ParameterTypeDescription
nameMaybeRefOrGetter<string>The cookie name (can be reactive)
initialValueMaybeRefOrGetter<T>The initial/default value
options?UseCookieOptions<T, Shallow>Options

Returns

UseCookieReturn<T, Shallow>An object with state ref and isReady flag, also awaitable