useCookie Hook
useCookie Hook
Level 4 — Composables & State An auto-imported Nuxt composable that allows you to read, write, and reactively sync browser cookies seamlessly across both the Server and the Client.
1. Prerequisites
useStateHook — Similar hook patterns.- Universal Rendering (SSR) — The rendering strategy where cookies enable server-accessible state configuration.
2. Term Category
State Management (SSR-Friendly Cookie Composable): useCookie() manages browser and server HTTP cookies reactively during SSR and client runtime.
3. Explanation
Environment Context
- Server & Client
(1) Design Motivation — "Why did we design this?"
In standard web development, reading a cookie on the server requires parsing the raw req.headers.cookie string. Reading a cookie on the client requires parsing the messy document.cookie string. Furthermore, if you change a cookie in the browser, your Vue components won't automatically re-render unless you manually trigger an update.
useCookie solves all of these problems simultaneously. It provides a unified, SSR-friendly API that works exactly the same way on the Node server as it does in the browser. Better yet, the cookie is reactive—if you update the cookie's value, the UI instantly updates.
(2) Core Concept
Calling useCookie('key') returns a reactive Vue Ref.
- If you read
.value, Nuxt reads the cookie. - If you change
.value, Nuxt automatically sends theSet-Cookieheader (on the server) or updatesdocument.cookie(on the client).
<script setup lang="ts">
// If the cookie 'theme' doesn't exist, it defaults to 'light'
const theme = useCookie<string>('theme', {
default: () => 'light',
maxAge: 60 * 60 * 24 * 7 // Cookie expires in 7 days
});
const toggleTheme = () => {
// Mutating the value automatically updates the physical browser cookie!
theme.value = theme.value === 'light' ? 'dark' : 'light';
};
</script>
<template>
<div :class="theme">
<p>Current theme: {{ theme }}</p>
<button @click="toggleTheme">Toggle Theme</button>
</div>
</template>
(3) SSR Magic
Because cookies are sent to the server on every request, useCookie is the ultimate tool for persisting user preferences (like Dark Mode) or Auth Tokens. When the user visits the page, Nitro reads the cookie, renders the HTML using the dark theme, and sends the perfect HTML back to the browser. Zero flickering!
4. Common Mistakes & Pitfalls
Mistake 1: Trying to use localStorage for SSR-critical data
The mistake: Storing an Auth Token or a Theme preference in localStorage.
Why it's wrong: The server cannot read localStorage. If you store the theme in localStorage, the server must guess what the theme is (usually guessing "light"). When the browser loads, it reads localStorage, realizes the user wants "dark", and flashes the screen from white to black (causing a Hydration Mismatch).
Golden Rule: If a piece of data affects how the page is visually rendered on initial load, it MUST be stored in a cookie using useCookie so the server can access it.
Mistake 2: Mutating useCookie() Values directly in Un-Protected Client Scripts (Missing Cookie Options)
The mistake: Setting sensitive auth token const token = useCookie('token'); token.value = 'abc' without setting sameSite or secure options.
Why it's wrong: Default cookies omit security flags like sameSite and secure, exposing cookies to CSRF attacks. Configure security options in useCookie.
Incorrect:
const token = useCookie('token'); // Missing secure cookie options
Fix:
const token = useCookie('token', {
maxAge: 86400,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production'
});
Mistake 3: Attempting to Read useCookie() in Asynchronous Event Handlers Without Hydration Sync
The mistake: Expecting useCookie state changes on client to update native browser document.cookie synchronously without ref trigger.
Why it's wrong: useCookie() returns a Vue reactive Ref. Assigning cookie.value = null updates both cookie storage and reactive Vue state automatically.
Incorrect:
/* Manually parsing document.cookie after mutating useCookie ref */
Fix:
/* Mutate ref value directly: const session = useCookie('session'); session.value = null; */
5. Practice Exercises
Exercise 1: Reading and Writing Reactive Cookies with useCookie()
Scenario:
Create a theme toggle switcher persisting user preference (light or dark) in a cookie via useCookie().
Requirements:
- Execute
const theme = useCookie("theme_pref", { default: () => "light" }).
Answer
Implementation
<script setup lang="ts">
const theme = useCookie<string>("theme_pref", {
default: () => "light",
maxAge: 60 * 60 * 24 * 365 // 1 year expiry
});
function toggleTheme() {
theme.value = theme.value === "light" ? "dark" : "light";
}
</script>
<template>
<div>
<p>Current Theme: {{ theme }}</p>
<button @click="toggleTheme">Toggle Theme</button>
</div>
</template>
Technical Explanation
useCookie()creates an SSR-friendly reactive wrapper around HTTP cookies.- On the server during SSR, it reads incoming request
Cookieheaders and appendsSet-Cookieresponse headers. - On the client, mutating
theme.valueupdatesdocument.cookiereactively.
Exercise 2: Configuring Secure Cookie Options
Scenario:
Configure an authentication session cookie with httpOnly: false, sameSite: "lax", and secure: true.
Requirements:
- Configure cookie options in
useCookie().
Answer
Implementation
const authToken = useCookie<string | null>("auth_token", {
maxAge: 60 * 60 * 24, // 24 hours
sameSite: "lax",
secure: true,
path: "/"
});
Technical Explanation
sameSite: "lax"protects cookies against Cross-Site Request Forgery (CSRF) attacks.secure: trueguarantees cookies are transmitted exclusively over encrypted HTTPS connections.path: "/"ensures cookie availability across all application route paths.
Exercise 3: Clearing Cookies on Logout
Scenario:
Clear an existing session cookie by setting its value to null or undefined.
Requirements:
- Set
cookie.value = null.
Answer
Implementation
<script setup lang="ts">
const userSession = useCookie("user_session");
function handleLogout() {
userSession.value = null; // Emits Set-Cookie with past expiration date!
navigateTo("/login");
}
</script>
<template>
<button @click="handleLogout">Clear Session & Logout</button>
</template>
Technical Explanation
- Setting
useCookie()value tonullorundefinedinstructs Nuxt to send aSet-Cookiedeletion header (Expires=Thu, 01 Jan 1970 00:00:00 GMT). - Clears cookie state in both browser and server memory contexts.
- Standard session destruction method.
6. Related Terms
useStateHook — The non-persistent alternative touseCookie.- Universal Rendering (SSR) — Why reading cookies on the server is so important.
7. Key Takeaways
useCookiereturns a reactiveReflinked to a physical browser cookie.- It works flawlessly on both the Server and the Client.
- Mutating
.valueautomatically updates the cookie. - It is the preferred way to store data that the Server needs to know about (Auth, Themes, Language preferences).