10-nuxtjsTermsLevel_04useCookie 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


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 the Set-Cookie header (on the server) or updates document.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.


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:

  1. 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

  1. useCookie() creates an SSR-friendly reactive wrapper around HTTP cookies.
  2. On the server during SSR, it reads incoming request Cookie headers and appends Set-Cookie response headers.
  3. On the client, mutating theme.value updates document.cookie reactively.

Scenario: Configure an authentication session cookie with httpOnly: false, sameSite: "lax", and secure: true.

Requirements:

  1. 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

  1. sameSite: "lax" protects cookies against Cross-Site Request Forgery (CSRF) attacks.
  2. secure: true guarantees cookies are transmitted exclusively over encrypted HTTPS connections.
  3. 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:

  1. 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

  1. Setting useCookie() value to null or undefined instructs Nuxt to send a Set-Cookie deletion header (Expires=Thu, 01 Jan 1970 00:00:00 GMT).
  2. Clears cookie state in both browser and server memory contexts.
  3. Standard session destruction method.


7. Key Takeaways

  • useCookie returns a reactive Ref linked to a physical browser cookie.
  • It works flawlessly on both the Server and the Client.
  • Mutating .value automatically updates the cookie.
  • It is the preferred way to store data that the Server needs to know about (Auth, Themes, Language preferences).
Built with LogoFlowershow