Want to bake up some delicious Nuxt cookies? Look no further than this comprehensive guide full of practical use cases and all the syntaxes you need to know.
Get notified when we release new tutorials, lessons, and other expert Nuxt content.
Cookies are an essential part of web development, allowing websites to store small pieces of data on the client-side. In Nuxt 3, working with cookies has become even more straightforward and powerful. This guide will walk you through everything you need to know about using cookies in your Nuxt 3 applications.
In Nuxt 3, cookies can be handled both on the server-side and client-side. Nuxt provides a unified API through the useCookie
composable, which works in both environments for pages and components.
To get started with cookies in Nuxt 3, you don't need any additional setup or imports. The useCookie
composable is available out of the box and is auto-imported, which means you can use it directly in your components, pages, or composables without explicitly importing it.
To read a cookie, use the useCookie
composable:
const token = useCookie('token')
console.log(token.value) // Outputs the cookie value
To set a cookie, simply assign a value to the ref returned by useCookie
:
const token = useCookie('token')
token.value = 'my-new-token'
You can also pass options when creating the cookie:
const token = useCookie('token', {
maxAge: 60 * 60 * 24 * 7, // 1 week
path: '/',
secure: true,
httpOnly: true
})
token.value = 'my-secure-token'
Let's break down each of these options:
maxAge
: This option sets the maximum age of the cookie in seconds. In the example, it's set to 60 * 60 * 24 * 7, which calculates to 604,800 seconds or 7 days. After this period, the cookie will expire and be automatically deleted by the browser.path
: This option specifies the path on the server for which the cookie is valid. Setting it to '/' means the cookie is available for all pages on the site. If you set it to '/admin', for example, the cookie would only be available for pages under the /admin path.secure
: When set to true
, this option ensures that the cookie is only transmitted over HTTPS. This is crucial for protecting sensitive information, as it prevents the cookie from being transmitted over unsecured connections.httpOnly
: Setting this to true
makes the cookie inaccessible to JavaScript's Document.cookie API. This is a security measure to help prevent cross-site scripting (XSS) attacks. The cookie can still be sent to the server, but client-side scripts cannot read or manipulate it.Additional options you can use include:
domain
: Specifies the domain for which the cookie is valid. By default, it's the current domain.sameSite
: Controls how the cookie is sent with cross-site requests. Possible values are:
expires
: Sets a specific date for when the cookie should expire. This is an alternative to maxAge
.Here's an example using these additional options:
const userPreferences = useCookie('userPrefs', {
maxAge: 60 * 60 * 24 * 30, // 30 days
path: '/',
secure: true,
httpOnly: true,
domain: 'example.com',
sameSite: 'lax'
})
userPreferences.value = JSON.stringify({ theme: 'dark', language: 'en' })
Remember, the appropriate options to use depend on your specific use case and security requirements. Always consider the sensitivity of the data you're storing and the potential security implications when setting cookie options.
To delete a cookie, set its value to null
:
const token = useCookie('token')
token.value = null
Nuxt 3 provides convenient methods for handling cookies on the server-side within the server
directory. The getCookie
and setCookie
functions are auto-imported from h3, so you can use them directly in your server API routes or middleware without explicit imports.
Here's how you can work with cookies on the server:
export default defineEventHandler((event) => {
// Reading a cookie
const token = getCookie(event, 'token')
// Setting a cookie
setCookie(event, 'session', 'session-value', {
httpOnly: true,
secure: true,
maxAge: 60 * 60 * 24 * 7 // 1 week
})
// Your route logic here
return {
message: 'Cookie handled on server'
}
})
In this example:
getCookie(event, 'token')
reads the value of the 'token' cookie.setCookie(event, 'session', 'session-value', options)
sets a new 'session' cookie with the specified options.The setCookie
function accepts the same options as the client-side useCookie
composable, allowing you to set properties like httpOnly
, secure
, maxAge
, etc.
Cookies in Nuxt 3 applications are versatile and can be used for various purposes. Here are some common use cases:
const authToken = useCookie('auth-token', {
maxAge: 60 * 60 * 24 * 7, // 1 week
secure: true,
httpOnly: true
})
// After successful login
authToken.value = 'user-auth-token'
const theme = useCookie('theme', {
default: () => 'light',
watch: true
})
// Toggle theme
function toggleTheme() {
theme.value = theme.value === 'light' ? 'dark' : 'light'
}
const lang = useCookie('lang', {
default: () => 'en',
maxAge: 60 * 60 * 24 * 30 // 30 days
})
// Set language
function setLanguage(newLang) {
lang.value = newLang
}
const cart = useCookie('shopping-cart', {
default: () => [],
watch: true,
encode: value => JSON.stringify(value),
decode: value => JSON.parse(value)
})
// Add item to cart
function addToCart(item) {
cart.value.push(item)
}
const cookieConsent = useCookie('cookie-consent', {
default: () => ({ necessary: true, analytics: false, marketing: false }),
maxAge: 60 * 60 * 24 * 365, // 1 year
encode: value => JSON.stringify(value),
decode: value => JSON.parse(value)
})
// Update consent
function updateConsent(category, value) {
cookieConsent.value[category] = value
}
const formData = useCookie('form-autosave', {
default: () => ({}),
watch: true,
maxAge: 60 * 10, // 10 minutes
encode: value => JSON.stringify(value),
decode: value => JSON.parse(value)
})
// Auto-save form data
function autoSaveForm(data) {
formData.value = data
}
Remember to always consider the nature of the data you're storing in cookies and apply appropriate security measures, especially for sensitive information.
httpOnly
flag for sensitive data to prevent XSS attacks.secure
flag to ensure cookies are only transmitted over HTTPS.By following this guide, you should now have a solid understanding of how to work with cookies in Nuxt 3. Remember to always consider security and privacy when implementing cookie-based features in your applications.
In this guide, we've explored the powerful cookie handling capabilities of Nuxt 3, from basic usage to advanced techniques. We've covered the useCookie
composable, server-side handling, common use cases, and important security considerations.
By mastering these concepts, you'll be able to create more dynamic, personalized, and secure Nuxt 3 applications. Remember to always prioritize user privacy and adhere to data protection regulations when working with cookies.
To deepen your Nuxt 3 knowledge even further, consider checking out the Mastering Nuxt course. This comprehensive course will take your Nuxt skills to the next level, covering advanced topics and best practices.