How to Read and Write Cookies in Nuxt 3

Learn how to read, write and manage cookies in Nuxt 3 using the useCookie built-in composable.

Mostafa Said
Nuxt 3

Mastering Nuxt 3 course is here!

Get notified when we release new tutorials, lessons, and other expert Nuxt content.

Click here to view the Nuxt 3 course

Ever wondered how your favorite websites remember your login details, preferences, or even track your cart items across sessions? The secret lies in cookies! These tiny pieces of data play a massive role in enhancing user experience and maintaining state across web applications.

In this comprehensive guide, we'll explore how to read, write and manage cookies in Nuxt 3. Whether you're building a dynamic web app or a simple blog, mastering cookies will level up your development game.

Introduction to Nuxt 3

Nuxt 3 is a powerful framework built on top of Vue.js, designed to make the development of universal applications (i.e., applications that can be rendered both on the server and client side) seamless and efficient. It provides an intuitive file-based routing system, server-side rendering (SSR), and numerous features that simplify complex tasks like state management and static site generation. To learn more about Nuxt and become a Nuxt expert, checkout the Mastering Nuxt 3 course.

One of Nuxt's standout features is its easy management of user cookies. But before we get to that, let's first understand what cookies are.

Understanding Cookies

Cookies are small pieces of data stored on the client side that can be used to remember information about the user across different sessions. They are key to building stateful web applications and can store user preferences, session information, and more. Let’s go through some of its benefits:

  1. State Management: Maintain user state across different pages and sessions.
  2. User Preferences: Store user-specific settings like themes, language preferences, etc.
  3. Session Management: Handle authentication and track user sessions.
  4. Analytics: Collect data on user interactions to improve user experience.

In other words, cookies are all about storing retrievable data. This raises an important question: how do cookies differ from other data storage mechanisms?

Cookies Compared to Other Data Storing Techniques

The two other popular ways to store data in web apps are JavaScript state management solutions and LocalStorage.

Cookies vs. State Management Solutions

While state management solutions like Pinia offer powerful tools for handling state in Vue applications, cookies provide unique advantages:

  • Persistence Across Sessions: Cookies persist data even after the browser is closed, unlike in-memory state solutions.
  • Server-Side Compatibility: Cookies can be read and written on the server, making them ideal for SSR applications. Even though state management solutions like Pinia can also work on the server-side of the app, the stored data can still be lost with a single hard refresh, which is not the case for cookies.
  • Lightweight: For small pieces of state, cookies can be more efficient than setting up a full state management solution.

Cookies vs. LocalStorage

LocalStorage is another common client-side storage solution, but cookies have distinct benefits:

  • Server Access: Cookies are sent with every HTTP request, allowing the server to access them directly.
  • Expiration Control: Cookies can have precise expiration times, which isn't possible with LocalStorage.
  • Security: Cookies can be secured with attributes like HttpOnly and Secure to protect sensitive data.

Managing Cookies in Nuxt 3

In Nuxt 3, managing cookies is made easy with the useCookie composable. This Vue composable is SSR-friendly, meaning it works seamlessly in both server-side and client-side contexts.

Getting Started with useCookie

The useCookie composable is used to read and write cookies within your Nuxt 3 application. It automatically serializes and deserializes cookie values to JSON, making it easy to work with complex data types.

const cookie = useCookie(name, options)

Basic Example

Here's a simple example from the official Nuxt 3 docs of using useCookie to create a cookie called counter.

<script setup lang="ts">
// Define a variable ref and set it's value to useCookie()
// Provide the useCookie composable with a name for your cookie
const counter = useCookie('counter')

// Make changes to the ref, and it will reflect the changes on the stored cookie
counter.value = counter.value || Math.round(Math.random() * 1000)
</script>

<template>
  <div>
    <h1>Counter: {{ counter.value || '-' }}</h1>
    <button @click="counter.value = null">reset</button>
    <button @click="counter.value--">-</button>
    <button @click="counter.value++">+</button>
  </div>
</template>

If the cookie doesn't exist, it is initially set to a random value. Whenever we update the counter variable, the cookie is updated accordingly. After updating, the value will persist even after a hard refresh, maintaining the final value assigned to the cookie.

Advanced Options

The useCookie composable accepts several options to modify the behavior of cookies:

  • maxAge / expires: Set the expiration of the cookie.
  • httpOnly: When set to true, the cookie is not accessible via JavaScript.
  • secure: When set to true, the cookie is only sent over HTTPS connections.
  • partitioned: An experimental attribute for partitioned cookies.
  • domain: Specify the domain the cookie applies to.
  • path: Specify the path the cookie applies to.
  • sameSite: Control cross-site request handling for the cookie.
  • encode / decode: Functions to encode and decode the cookie value.
  • default: A function to provide the cookie's default value.
  • readonly: Access the cookie value without the ability to set it.
  • watch: Control if and how the cookie ref data is watched for changes.

Example with Options

Let's look at an example from the official docs where we use some of these options:

<script setup lang="ts">
const user = useCookie('userInfo', {
// Here we're using the default option to assign a default value for the cookie
  default: () => ({ score: 0 }),
  // And here we say that we don't want to watch for data changes in the cookie ref
  watch: false
})

if (user.value && user.value !== null) {
  user.value.score++; // userInfo cookie not updated with this change
}
</script>

<template>
  <div>User score: {{ user.value?.score }}</div>
</template>

Sometimes, you might need to manually refresh cookie values. This can be done using the refreshCookie function which is auto-imported by Nuxt (Available only in versions +3.10). It’s designed to refresh cookie value returned by useCookie ****. All we need to do is to provide the function with the cookie name.

refreshCookie('cookieName')

Cookies in API Routes

You can also manage cookies within your Nuxt’s server API routes using the getCookie and setCookie functions from the h3 package.

Example: API Route with Cookies

Here's an example of an API route that reads and sets a cookie:

import { defineEventHandler, getCookie, setCookie } from 'h3'

export default defineEventHandler(event => {
  // Read counter cookie
  let counter = getCookie(event, 'counter') || 0

  // Increase counter cookie by 1
  setCookie(event, 'counter', ++counter)

  // Send JSON response
  return { counter }
})

Conclusion

Cookies are an essential part of web development, enabling you to maintain state, store user preferences, manage sessions, and more. Nuxt 3 simplifies the process of working with cookies through the useCookie composable, which provides a convenient and SSR-friendly way to read and write cookies. By leveraging the powerful options and functionality provided by useCookie, you can create robust and stateful Nuxt 3 applications.

Whether you're just getting started with Nuxt 3 or looking to enhance your existing projects, checkout the Mastering Nuxt 3 course from Vue School, It’s a great resource to sharpen your skills.

Mostafa Said
Mostafa is a full-stack developer, a full-time Instructor at Vue School, and a Vue.js Jedi.

Follow MasteringNuxt on