Learn how to read, write and manage cookies in Nuxt 3 using the useCookie built-in composable.
Get notified when we release new tutorials, lessons, and other expert Nuxt content.
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.
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.
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:
In other words, cookies are all about storing retrievable data. This raises an important question: how do cookies differ from other data storage mechanisms?
The two other popular ways to store data in web apps are JavaScript state management solutions and LocalStorage.
While state management solutions like Pinia offer powerful tools for handling state in Vue applications, cookies provide unique advantages:
LocalStorage is another common client-side storage solution, but cookies have distinct benefits:
HttpOnly
and Secure
to protect sensitive data.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.
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)
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.
The useCookie
composable accepts several options to modify the behavior of cookies:
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')
You can also manage cookies within your Nuxt’s server API routes using the getCookie
and setCookie
functions from the h3 package.
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 }
})
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.