How to store data to local storage with Nuxt.js

Giffary picture Giffary · Nov 22, 2017 · Viewed 21.4k times · Source

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 where user can put username and password into the form the send it to server (via api) to check, if login data is correct, the api will return one token key then I will store this key to verify is user is authen and use it with other api.

I found some example but build with vuejs here https://auth0.com/blog/build-an-app-with-vuejs/ but I don't have an idea how to change it to nuxtjs.

Any I have read https://github.com/robinvdvleuten/vuex-persistedstate which I can plug in to my project but I would like to see other solution.

Regards.

Answer

Vamsi Krishna picture Vamsi Krishna · Nov 22, 2017

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