The Ultimate Guide to Cookies In Nuxt 3

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.

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

Introduction

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.

Understanding Cookies in Nuxt 3

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.

Reading Cookies

To read a cookie, use the useCookie composable:

const token = useCookie('token')
console.log(token.value) // Outputs the cookie value

Writing Cookies

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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:

  1. domain: Specifies the domain for which the cookie is valid. By default, it's the current domain.
  2. sameSite: Controls how the cookie is sent with cross-site requests. Possible values are:
    • 'strict': The cookie is only sent to the same site as the one that originated it.
    • 'lax': The cookie is not sent on cross-site requests, but is sent when a user navigates to the origin site from an external site.
    • 'none': The cookie is sent on both same-site and cross-site requests.
  3. 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.

Deleting Cookies

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.

Common Use Cases

Cookies in Nuxt 3 applications are versatile and can be used for various purposes. Here are some common use cases:

  1. User Authentication
    Storing authentication tokens in cookies is a common practice for maintaining user sessions:
    const authToken = useCookie('auth-token', {
      maxAge: 60 * 60 * 24 * 7, // 1 week
      secure: true,
      httpOnly: true
    })
    
    // After successful login
    authToken.value = 'user-auth-token'
    
  2. Theme Preferences
    Remembering user's theme preferences across sessions:
    const theme = useCookie('theme', {
      default: () => 'light',
      watch: true
    })
    
    // Toggle theme
    function toggleTheme() {
      theme.value = theme.value === 'light' ? 'dark' : 'light'
    }
    
  3. Language Settings
    Storing user's language preference:
    const lang = useCookie('lang', {
      default: () => 'en',
      maxAge: 60 * 60 * 24 * 30 // 30 days
    })
    
    // Set language
    function setLanguage(newLang) {
      lang.value = newLang
    }
    
  4. Shopping Cart
    Maintaining shopping cart data across page reloads:
    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)
    }
    
  5. Consent Management
    Storing user's cookie consent preferences:
    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
    }
    
  6. Form Auto-Save
    Saving form data to prevent loss on accidental page reload:
    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.

Best Practices and Security Considerations

  1. Always use the httpOnly flag for sensitive data to prevent XSS attacks.
  2. Use the secure flag to ensure cookies are only transmitted over HTTPS.
  3. Set appropriate expiration times for your cookies.
  4. Be mindful of GDPR and other privacy regulations when using cookies.

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.

Conclusion

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.

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

Follow MasteringNuxt on