NuxtJS set Cookie in Middleware

Viewed 21952

I'm building a nuxtjs app and try to set a cookie from a global middleware. I found this contribution on GitHub which shows a method to do this.

So I implemented my middleware like this

export default function ({ isServer, res, query }) {
  if (query.lang) {
    if (isServer) {
      res.setHeader("Set Cookie", [`lang=${query.lang}`]);
    } else {
        document.cookie = `lang=${query.lang}`;
    }
  }
}

My problem is that when I visit my app with ?lang=xxx as a parameter, I'm always running into the else block of my if condition. So I get the error

document is not defined

Has anyone a idea what is wrong with my code. I can't see a difference to the code published on github.

3 Answers

You should use cookie-universal-nuxt.

Add this in your module section in nuxt.config.js:
['cookie-universal-nuxt', { alias: 'cookiz' }],

You can use it directly in the store with nuxtServerInit:

async nuxtServerInit({ commit, state, dispatch },
    { app, store, route, req, res, error, redirect }
) {
    app.$cookiz.set('lang', route.query.lang)
})

Or in a middleware:

export default function ({ app, res, query }) {
  if (query.lang) {
    app.$cookiz.set('lang', query.lang)
  }
}

You can using helpers from nuxt by using setCookie and custom middleware https://nuxtjs.org/docs/configuration-glossary/configuration-servermiddleware/

middlewares/cookies.ts

export default function (req, res, next) {
 let cookie = getCookie(req, '_id') || 'random_value'
 setCookie(res, '_id', cookie)

// Don't forget to call next at the end if your middleware is not an endpoint
 next()
}

Also update your nuxt.config.ts

export default defineNextConfig({
 // ...
 router: {
    middleware: ["cookies"],
 }
})

In Nuxt 3 and Nuxt 2 Bridge you can use useCookie

Nuxt provides an SSR-friendly composable to read and write cookies.

const lang = useCookie('lang')
lang.value = ''
Related