As you know, nuxtjs is server side rendering and there is no good example how to store data into localstorage which is client side.
My work is need to build login form w
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
You can use process.browser
to check it's in browser or not.
export default {
created() {
this.storeToken();
},
methods:{
storeToken(token){
if(process.browser){
localStorage.setItem("authToken", token);
}
}
}
}
You also call this method in mounted without check process.browser
.
export default {
mounted() {
this.storeToken();
},
methods:{
storeToken(token){
localStorage.setItem("authToken", token);
}
}
}
nuxtjs provides you with process.browser
to tell it to execute only on the client side
so use it like this:
methods:{
storeToken(token){
if(process.browser){
localStorage.setItem("authToken", token);
}
}
}
see this link for more info