How to store data to local storage with Nuxt.js How to store data to local storage with Nuxt.js vue.js vue.js

How to store data to local storage with Nuxt.js


Nuxt provides you with process.client to tell it to execute only on the client side

so use it like this:

methods: {  storeToken(token) {    if(process.client) {      localStorage.setItem("authToken", token)    }  }}

Check this link for more info.


You can use process.client to check it's on client-side or not.

export default {  created() {    this.storeToken();  },  methods:{    storeToken(token){      if(process.client){          localStorage.setItem("authToken", token);      }    }  }}

You also call this method in mounted without check process.client.

export default {  mounted() {    this.storeToken();  },  methods:{    storeToken(token){       localStorage.setItem("authToken", token);    }  }}


A little late to the party, but I was having similar problems.

But first I would recommend you to use cookies for saving a key/token/jwt.The reason being that localStorage can be hijacked through JS api's and cookies can be safeguarded from that. You will however have to safeguard your token from CSFR. That can be done by having a look at the Refence and Origin headers server side. This guy wrote a good post on how to do that: How to protect your HTTP Cookies

As for accessing localStorage from Nuxt, here we go:

If you are running Nuxt and haven't told it to run in spa mode it will run in universal mode. Nuxt defines universal mode as:

Isomorphic application (server-side rendering + client-side navigation)

The result being that localStorage is not defined serverside and thus throws an error.

The give away for me was that console logging from middleware files and Vuex outputted to terminal and not the console in developer tools in the browser.

if you want to read more about my solution you can find it here: localStorage versus Nuxt's modes