Get a browser cookie, and pass it to the server side rendering on nuxt js

11,870

You can store the needed info in both local storage & cookie, e.g.

import Cookie from 'js-cookie'
....
setCookie(state, value) {
  if (process.client) {
    localStorage.setItem('cookie', value);
  }
  Cookie.set('cookie', value)
}

To read it (cookies are included in the request automatically)

getCookie(context, req) {
  // if server
  if (req) {
    if (req.headers.cookie) {
      const cookie = req.headers.cookie.split(';').find(...)
    }
  }
  // if client
  if (process.client) {
    const cookie = localStorage.getItem('cookie');
  }
}

And to remove

removeCookie(state) {
  if (process.client) {
    localStorage.removeItem('cookie');
  }
  Cookie.remove('cookie');
}
Share:
11,870
soarinblue
Author by

soarinblue

Exploring the life. Software Engineer. Full Stack Web Engineer. Web Front-End Engineer.

Updated on June 04, 2022

Comments

  • soarinblue
    soarinblue almost 2 years

    I develop a project with nuxt js. And I get problem like this below.

    • I get result from restful api of backend with asynchronous ajax request.
    • I need add the result as a header to every quest with the ajax library of axios.
    • So I save the result on browser cookie.
    • When I need the result, I get it from cookie, and attach it on axios request.

    Now, the problem is on the server side rendering, I can not get the browser cookie.

    What am I gonna do with the problem?

  • ßãlãjî
    ßãlãjî about 3 years
    is this plugin file? or where placed?
  • Pranciskus
    Pranciskus about 3 years
    I have those inside vuex store