cookiesnuxt.js

Can't set cookie on server side Nuxt.js


I am using initial Nuxt function, that is invoked on reload, to set important data like userId and token. I can read data from cookie, but I can't save data to cookie.

initAuth(context, req) {
try {
  const cookie = req.headers.cookie
  if (req && cookie) {
    let token = getCookieServerSide('token', cookie)
    let userId = getCookieServerSide('userId', cookie)
    let deviceId = getCookieServerSide('deviceId', cookie)

    if (token) {
      context.commit('SET_TOKEN', { token })
    }
    if (userId) {
      userId = parseInt(userId)
      context.commit('users/SET_USER_ID', userId, { root: true })
    }
    if (!deviceId) {
      deviceId = generateUniqueId()
      setCookie('deviceId', deviceId)
    }
    context.commit('SET_DEVICE_ID', deviceId)
  }
} catch (error) {}

This is initial method, and setCookie looks like this:

export const setCookie = (name, value) => {
  Cookie.set(name, value)
}

By reading different comments this should be valid solution, but cookie isn't saved


Solution

  • Your current cookie lib is only compatible with an execution on the front-end code.

    To set cookie on both client and server sides, you have to use a lib that supports an universal usage, like universal-cookie.

    With Nuxt, you can use cookie-universal-nuxt to set, get and remove cookies in both client and server side, based on the previous lib.