Handling Cookies in a Nuxt App

Handling Cookies in a Nuxt App

Learn to manage cookies in Nuxt with SSR-friendly useCookie and server utilities, refresh values, support SPA mode, and secure sensitive cookies with httpOnly, secure, and sameSite options.

Reza Baar

Reza Baar

November 17, 2026

Cookies show up in almost every real app: a session token, a theme preference, a "you've seen this banner" flag, a cookie-consent choice. They look simple, but Nuxt adds its own twists. Your code can run on the server during SSR and again on the client, and the obvious browser API (document.cookie) only exists in one of those places. In this post, we'll cover how to handle cookies properly in Nuxt, both in SSR apps and in SPA mode, from the useCookie composable to server-side reading and writing to the security options you shouldn't skip.

Why document.cookie Falls Short

If you've written plain JavaScript, your instinct is to reach for document.cookie. In a Nuxt app rendered on the server, that breaks, because document doesn't exist on the server. When a page renders during SSR, there's no browser, no DOM, and no document. Code that touches document.cookie either crashes or silently does nothing on the server, then behaves differently once it hydrates on the client.

That mismatch is a big reason Nuxt provides its own cookie handling. You want a cookie you can read while rendering on the server (to decide what HTML to send) and the same cookie available on the client after hydration. useCookie gives you exactly that.

The useCookie Composable

useCookie is an SSR-friendly composable that reads and writes cookies and works the same on both server and client. You call it with a cookie name, and it returns a reactive ref:

const counter = useCookie('counter');

// Read it
console.log(counter.value);

// Write it: this updates the cookie
counter.value = 42;

Writing to the ref updates the cookie. On the server, Nuxt sets it via the response's Set-Cookie header; on the client, it updates the browser's cookie. You work with a normal reactive ref and Nuxt handles the mechanics on both sides.

One convenience worth knowing is that the ref automatically serializes and deserializes to JSON, so you can store objects and arrays directly without stringifying them yourself:

const user = useCookie('user');
user.value = { name: 'Ada', theme: 'dark' }; // stored as JSON

const list = useCookie('list');
list.value = [1, 2, 3]; // also fine

useCookie only works inside the Nuxt context, meaning in your pages, components, composables, and plugins. It isn't meant to be called in server routes, which have their own API we'll get to.

useCookie takes an options object as its second argument, and most of these map straight to the standard cookie attributes. The ones you'll use most:

const token = useCookie('token', {
  maxAge: 60 * 60 * 24 * 7, // lifespan in seconds (here, one week)
  expires: new Date('2026-12-31'), // or an explicit expiry date
  path: '/', // which paths the cookie applies to
  domain: 'example.com', // which domain it belongs to
  sameSite: 'lax', // 'strict' | 'lax' | 'none' — cross-site behavior
  secure: true, // only sent over HTTPS
  httpOnly: true, // not readable from client-side JS (server-set only)
  default: () => 'guest', // value when the cookie isn't set yet
});

A couple of these deserve a closer look because they behave in ways that surprise people.

The default option is a function that provides a fallback value when the cookie doesn't exist yet. It doesn't write the cookie; it just gives the ref something to return until you set a real value. It's handy for avoiding null checks everywhere:

const theme = useCookie('theme', { default: () => 'light' });
// theme.value is 'light' even before the user has chosen one

The watch option controls whether changes to the ref sync back to the cookie. By default it's on, so writing cookie.value = x updates the cookie. You can set it to false if you want to manage writes manually, or 'shallow' to only react to top-level changes. This matters for objects: mutating a nested property of a cookie object may not trigger a write, so reassign the whole value when you want it persisted.

A Real Example: A Persistent Theme Preference

Let's tie this together with something you'd actually build: a dark-mode toggle that persists across reloads and renders correctly on the server, with no flash of the wrong theme.

// composables/useTheme.ts — a theme cookie shared across the app
export function useTheme() {
  const theme = useCookie<'light' | 'dark'>('theme', {
    default: () => 'light',
    maxAge: 60 * 60 * 24 * 365, // remember for a year
  });

  function toggle() {
    theme.value = theme.value === 'light' ? 'dark' : 'light';
  }

  return { theme, toggle };
}
<!-- components/ThemeToggle.vue -->
<script setup lang="ts">
const { theme, toggle } = useTheme();
</script>

<template>
  <button @click="toggle">
    Switch to {{ theme === 'light' ? 'dark' : 'light' }} mode
  </button>
</template>

Because useCookie reads the cookie during SSR, the server already knows the user's theme when it renders the page. You can apply it to the initial HTML, so the correct theme is there from the first paint instead of flickering after hydration. That flash-of-wrong-theme problem is exactly what client-only cookie handling can't solve, and it's the clearest argument for doing cookies the Nuxt way.

Reading and Writing Cookies on the Server

useCookie covers pages and components, but a lot of cookie work belongs on the server: setting a session after login, reading an auth token in an API route, clearing a cookie on logout. For that, Nuxt gives you utilities from h3 (the server engine's HTTP layer): getCookie, setCookie, and deleteCookie. They're auto-imported in your server/ directory, so you use them without importing.

Here's a server route that reads a counter cookie, increments it, and writes it back:

// server/api/counter.ts — reads, increments, and re-sets a counter cookie
export default defineEventHandler((event) => {
  const current = Number(getCookie(event, 'counter')) || 0;
  const next = current + 1;

  setCookie(event, 'counter', String(next), {
    maxAge: 60 * 60 * 24,
    httpOnly: true,
    sameSite: 'lax',
  });

  return { counter: next };
});

The server utilities take the request event as their first argument, since on the server a cookie is tied to a specific request and response rather than a global document. setCookie accepts the same options as useCookie, so httpOnly, secure, sameSite, and the rest all work the same way.

To remove a cookie, use deleteCookie:

// server/api/logout.post.ts — clears the session cookie
export default defineEventHandler((event) => {
  deleteCookie(event, 'session');
  return { ok: true };
});

Reading cookies on the server is also what you do in server middleware, for example to check an auth token on every request before a route handler runs:

// server/middleware/auth.ts — reads the session cookie on every request
export default defineEventHandler((event) => {
  const session = getCookie(event, 'session');
  if (session) {
    // attach the user to the event context for later handlers
    event.context.user = decodeSession(session);
  }
});

When to Use the Composable vs the Server Utilities

The split is straightforward once you see it. Use useCookie in pages, components, composables, and plugins: the parts of your app that render. Use getCookie / setCookie / deleteCookie in server/ routes and middleware: the parts that handle requests.

They can work on the same cookie. A login route sets a session cookie with setCookie (server-side, and ideally httpOnly), and your components read non-sensitive preference cookies with useCookie. The right tool depends on where the code runs, not on which cookie it is.

Refreshing a Cookie's Value

useCookie reads the cookie when the composable is created, but it doesn't poll for outside changes. If something else updates the cookie (a server route in response to a fetch, or another tab), your ref won't automatically reflect it. Nuxt provides refreshCookie to manually re-read a cookie's value:

async function updateCounter() {
  await $fetch('/api/counter'); // server updates the 'counter' cookie
  refreshCookie('counter'); // re-read it so the ref reflects the new value
}

const counter = useCookie('counter');

Reach for refreshCookie when you know a cookie changed somewhere useCookie couldn't observe, typically after a server round-trip that set a cookie.

Cookies in SPA Mode (No SSR)

Not every Nuxt app uses SSR. If you've set ssr: false in your config, your app is a single-page app that renders entirely in the browser. Luckily you don't have to change how you write cookie code.

useCookie still works in SPA mode. The difference is just where the work happens. With SSR, the initial cookie read occurs on the server as it renders; in SPA mode, there's no server render, so everything happens in the browser from the start. Because useCookie wraps the browser's cookie storage under the hood, it behaves correctly either way, and the same composable code runs unchanged.

The practical implication: writing your cookie logic with useCookie from the start means you can switch between SSR and SPA mode (or move a feature between them) without rewriting anything. The one thing to keep in mind is that in pure SPA mode you don't have a Nuxt server handling requests, so the server utilities (getCookie and friends) only apply if you're running Nuxt with a server. If you deploy as a static SPA with no server, server-side cookie handling isn't part of the picture, and any cookie reading an attacker shouldn't see (like a session) has to be validated by whatever backend you do talk to.

Security: The Important Options

Cookies often hold sensitive things, so a few options are worth treating as defaults rather than afterthoughts, especially for anything auth-related.

httpOnly makes a cookie unreadable from client-side JavaScript. This is the key defense for session tokens: if JavaScript can't read the cookie, neither can a script injected through an XSS attack. The catch, and it's an important one, is that an httpOnly cookie can only be set and read on the server. useCookie can't read it on the client (that's the point), so httpOnly cookies are the domain of the server utilities. Don't try to manage an auth token with useCookie on the client and expect httpOnly to work; set it server-side with setCookie.

secure ensures the cookie is only sent over HTTPS. Turn this on for anything sensitive in production. Be aware, as the Nuxt docs note, that a secure cookie won't be sent back by the browser over a plain HTTP connection, which can bite you in local development if you're not on HTTPS.

sameSite controls whether the cookie is sent on cross-site requests, which is your main lever against CSRF. 'strict' sends it only for same-site requests, 'lax' is a sensible default that allows top-level navigations, and 'none' allows cross-site sending but requires secure.

Putting it together, a session cookie set after login should look something like this, and it belongs on the server:

// server/api/login.post.ts — sets a hardened session cookie
export default defineEventHandler(async (event) => {
  const { token } = await authenticateUser(event);

  setCookie(event, 'session', token, {
    httpOnly: true, // not readable by client JS
    secure: true, // HTTPS only
    sameSite: 'lax', // CSRF protection
    maxAge: 60 * 60 * 24 * 7, // one week
    path: '/',
  });

  return { ok: true };
});

The rule of thumb: session and auth tokens are server-set, httpOnly, secure, and sameSite. Preference cookies (theme, language, UI state) that aren't sensitive can live happily in useCookie on the client.

If your app serves users in regions with privacy regulations (GDPR and similar), non-essential cookies (analytics, marketing) generally require consent before you set them. You can track the user's choice in a cookie itself:

const consent = useCookie<boolean>('cookie-consent', {
  default: () => false,
  maxAge: 60 * 60 * 24 * 365,
});

Then gate your non-essential cookies and scripts on consent.value. For anything beyond a simple banner, a dedicated module handles the details (consent categories, script blocking until consent) more thoroughly than a hand-rolled solution, and it's worth reaching for one rather than trying to get compliance right yourself.

Key Takeaways

  • document.cookie doesn't exist during SSR, which is why Nuxt provides its own cookie handling
  • useCookie is an SSR-friendly reactive ref for cookies, usable in pages, components, composables, and plugins
  • It serializes objects and arrays to JSON automatically, and the default option gives a fallback without writing the cookie
  • On the server, use getCookie, setCookie, and deleteCookie from h3 in routes and middleware
  • Use the composable where your app renders, and the server utilities where it handles requests
  • refreshCookie re-reads a cookie when it changed somewhere useCookie couldn't observe
  • useCookie works unchanged in SPA mode (ssr: false); only the server utilities depend on having a server
  • For auth, set cookies server-side with httpOnly, secure, and sameSite. httpOnly cookies can't be read by useCookie on the client, by design

Conclusion

Cookies in Nuxt come down to one distinction: where your code runs. The composable handles the rendering side and stays SSR-safe so you never touch document.cookie, and the server utilities handle requests and let you set hardened, httpOnly cookies that client JavaScript can't reach. Write your cookie logic with these tools from the start and it holds up whether you run SSR or ship a SPA, with the security properties you want baked in.

I hope this post has been helpful. Please let me know if you have any questions or comments. Happy coding!

Ready to prove your Nuxt skills?

Get certified in Nuxt

More Nuxt articles

Keep learning Nuxt. Then get certified when you are ready.