microcipcip / cookie-universal

Universal cookie plugin, perfect for SSR
525 stars 39 forks source link

Nuxt: Not able to set a cookie in nuxtServerInit #94

Closed IvoPereira closed 3 years ago

IvoPereira commented 3 years ago

Hi there!

I am using Vuex module mode and trying to set a cookie inside nuxtServerInit, but for some reason it does not seem to set anything at all.

A worth note, in server, it does not appear to log any kind of set cookie at all.

An example:

nuxtServerInit - store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const state = () => ({})

export const mutations = {}

export const actions = {
  nuxtServerInit(_, { $cookiz }) {
    // Setting a cookie
    $cookiz.set('set-inside-nuxtServerInit', 'does not work!')

    // This "set-inside-nuxtServerInit" cookie should be set when getting all set cookies, but it doesn't!
    console.log('set-inside-nuxtServerInit => ', $cookiz.getAll())
  },
}

Log in the server: set-inside-nuxtServerInit => {}

Log in the client: set-inside-plugin => {}

However, when trying to do the same inside a plugin I am perfectly able to do so (in the client):

plugin/example.js

export default ({ app }) => {
  // Setting a cookie
  app.$cookiz.set('set-inside-plugin', 'works in client only!')

  // This "set-inside-plugin" cookie is set when calling getAll() but only shows in client, not on server
  console.log('set-inside-plugin => ', app.$cookiz.getAll())
}

Log in the server: set-inside-plugin => {}

Log in the client: set-inside-plugin => Object { "set-inside-plugin": "works!" }

If it helps, my nuxt.config.js modules section:

  modules: [
    ['cookie-universal-nuxt', { alias: 'cookiz' }],
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    'nuxt-imagemin',
    '@nuxtjs/pwa',
  ],

Now some questions:

1) Why does the cookie is set on a plugin and not in nuxtServerInit? Am I missing something? 2) Why does the cookie is set only on client and not on server?

Thanks!

IvoPereira commented 3 years ago

Forget it. Turns out that somehow I had a target property set to static in my nuxt.config.js for some reason.

If anyone else stumbles on this, apart of target that should be as server (if you are using SSR obviously), mode should also be set to universal (it is the Nuxt default).

Thanks!