use-cookie
Parse a Cookie request header (or document.cookie) into name/value pairs.
| Package | @vizejs/composable/use-cookie |
| Own the source | vize lib pull composable:use-cookie |
| Runtime exports | COOKIE_ADAPTER_KEY, parseCookieHeader, provideCookieAdapter, serializeCookie, useCookie |
| Gzip budget | 4608 B |
Minimal setup
Use a Vue 3.5+ project with Vue SFC compilation configured (see Vite+ integration).
vp install @vizejs/composable
Import the entry directly. Call lifecycle-bound utilities inside <script setup> so cleanup follows the component scope; consult the runtime contract for this entry's SSR and hydration behavior.
import { COOKIE_ADAPTER_KEY, parseCookieHeader, provideCookieAdapter, serializeCookie, useCookie } from "@vizejs/composable/use-cookie";
Try it
Remember a theme in a cookie
Store a small preference in a cookie that the server can read on the next request.
What to observe: Use dark theme writes the cookie and shows Saved theme: dark. Forget preference removes it.
String cookies are stored as written; other defaults are stored as JSON. Pass path, sameSite, maxAge and other attributes as options.
Compare the initial and interacted states


Copy the example
Save this complete SFC in your Vue project. Its public imports and source are the same ones executed in the preview.
<script setup lang="ts">
import { useCookie } from "@vizejs/composable/use-cookie";
const { state: theme, remove } = useCookie("docs-example-theme", { path: "/", sameSite: "lax" });
</script>
<template>
<div class="composable-example">
<p>Remember a preference in a cookie so the server can read it on the next request.</p>
<div class="example-actions">
<button type="button" @click="() => (theme = 'light')">Use light theme</button>
<button type="button" @click="() => (theme = 'dark')">Use dark theme</button>
<button type="button" @click="() => remove()">Forget preference</button>
</div>
<output aria-live="polite">{{ theme ? `Saved theme: ${theme}` : "No saved theme." }}</output>
</div>
</template>
Runtime contract
| Utility | Category | Stability | SSR | Hydration | Cleanup | Targets | Host globals | Uses |
|---|---|---|---|---|---|---|---|---|
parseCookieHeader |
storage | experimental | safe | not-applicable | none | web, server, worker, native, desktop, terminal | — | — |
serializeCookie |
storage | experimental | safe | not-applicable | none | web, server, worker, native, desktop, terminal | — | — |
provideCookieAdapter |
storage | experimental | safe | not-applicable | none | web, server, worker, native, desktop, terminal | — | — |
useCookie |
storage | experimental | safe | stable | reactive-scope | web, server, worker, native, desktop, terminal | window |
parseCookieHeader, serializeCookie, tryOnScopeDispose, useMounted |
API
parseCookieHeader
Parse a Cookie request header (or document.cookie) into name/value pairs. Values are percent-decoded; the first occurrence of a name wins, matching how browsers order more specific cookies first. Pure and SSR-safe.
function parseCookieHeader(header: string): Record<string, string>
serializeCookie
Serialize one cookie as a Set-Cookie header value (also accepted by document.cookie). The value is percent-encoded so any string is safe.
function serializeCookie( name: string, value: string, attributes: CookieAttributes = {}, ): string
COOKIE_ADAPTER_KEY
Injection key for an app- or subtree-wide CookieAdapter.
const COOKIE_ADAPTER_KEY: InjectionKey<CookieAdapter>
provideCookieAdapter
Provide a CookieAdapter to descendant components (for example the request/response pair of a server render). Must be called during setup; use app.provide(COOKIE_ADAPTER_KEY, adapter) for a whole app.
function provideCookieAdapter(adapter: CookieAdapter): void
useCookie
Read and write one cookie with a typed default.
function useCookie<Value>( name: string, options: UseCookieOptions<Value> & { readonly default: Value }, ): CookieControls<Value>
useCookie
Read and write one raw string cookie; absent cookies are undefined.
function useCookie( name: string, options?: UseCookieOptions<string>, ): CookieControls<string | undefined>
useCookie
Synchronize a typed reactive value with one cookie, on the server and in the browser. The adapter is resolved from options.adapter, then from COOKIE_ADAPTER_KEY (see provideCookieAdapter), then from document.cookie in browsers. During a server render with an adapter the value comes from the request Cookie header and assignments emit Set-Cookie headers through adapter.write, so server and client render the same value and hydrate without a mismatch. Without any adapter (plain SSR) the default is used and nothing is written. String defaults are stored raw; other defaults as JSON checked by validate (by default: same kind as the default). Assigning undefined (or calling remove) expires the cookie. Cookies are written with Path=/ unless path is given. Failures never throw; they are exposed through error and onError. The write watcher stops with the owning reactive scope.
function useCookie<Value>( name: string, options: UseCookieOptions<Value> = {}, ): CookieControls<Value | undefined>
// server entry: app.provide(COOKIE_ADAPTER_KEY, { read: () => req.headers.cookie ?? "",
// write: (value) => res.appendHeader("Set-Cookie", value) });
const { state: locale } = useCookie("locale", { default: "en", maxAge: 31_536_000 });
Types
CookieAttributes
Attributes written with a cookie (RFC 6265bis).
| Member | Type | Description |
|---|---|---|
path? |
string |
Path attribute. |
domain? |
string |
Domain attribute. |
maxAge? |
number |
Max-Age in integer seconds; 0 or less expires the cookie. |
expires? |
Date |
Expires date. |
sameSite? |
CookieSameSite |
SameSite policy. "none" requires secure. |
secure? |
boolean |
Secure flag. |
httpOnly? |
boolean |
HttpOnly flag. Only honored by server adapters: browsers ignore cookies with this flag written through document.cookie. |
partitioned? |
boolean |
Partitioned flag (CHIPS). Requires secure. |
CookieAdapter
Request/response bridge used by useCookie. On the server, read returns the incoming Cookie header and write appends a Set-Cookie header to the response. In the browser the default adapter reads and writes document.cookie.
| Member | Type | Description |
|---|---|---|
read |
() => string |
Return the current Cookie header (name=value; …). |
write |
(setCookie: string) => void |
Persist one serialized cookie (a Set-Cookie header value). |
CookieSerializer
Converts a cookie value to and from its string form.
| Member | Type | Description |
|---|---|---|
read |
(raw: string) => Value |
Decode the percent-decoded cookie value. Throwing selects the default. |
write |
(value: Value) => string |
Encode a value; the result is percent-encoded when written. |
CookieFailure
Failure observed while synchronizing a cookie.
| Member | Type | Description |
|---|---|---|
code |
CookieErrorCode |
Which synchronization step failed. |
name |
string |
Cookie name involved in the failure. |
cause |
unknown |
Exact thrown value, or the rejected candidate for "invalid-value". |
UseCookieOptions
Options for useCookie.
| Member | Type | Description |
|---|---|---|
path? |
string |
Path attribute. |
domain? |
string |
Domain attribute. |
maxAge? |
number |
Max-Age in integer seconds; 0 or less expires the cookie. |
expires? |
Date |
Expires date. |
sameSite? |
CookieSameSite |
SameSite policy. "none" requires secure. |
secure? |
boolean |
Secure flag. |
httpOnly? |
boolean |
HttpOnly flag. Only honored by server adapters: browsers ignore cookies with this flag written through document.cookie. |
partitioned? |
boolean |
Partitioned flag (CHIPS). Requires secure. |
default? |
Value |
Value used when the cookie is absent or unreadable. Also selects the serializer: strings are stored raw, everything else as JSON. |
serializer? |
CookieSerializer<Value> |
Explicit serializer. |
validate? |
(candidate: unknown) => candidate is Value |
Validation hook applied to every decoded value. |
adapter? |
CookieAdapter | null |
Request/response adapter. Takes precedence over an injected adapter. |
onError? |
(failure: CookieFailure) => void |
Observe failures. Failures never throw out of the composable. |
CookieControls
Reactive state and controls returned by useCookie.
| Member | Type | Description |
|---|---|---|
state |
Ref<Value> |
Writable cookie value; assignments write the cookie. |
supported |
Readonly<Ref<boolean>> |
Whether an adapter is attached. With the implicit document.cookie adapter inside a component it stays false until mounted, matching a server render without an adapter. |
error |
Readonly<ShallowRef<CookieFailure | undefined>> |
Most recent failure, cleared by the next success. |
refresh |
() => void |
Re-read the cookie from the adapter. |
remove |
() => void |
Expire the cookie and restore the default value. |