Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store data to local storage with Nuxt.js

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.

like image 701
Giffary Avatar asked Nov 22 '17 11:11

Giffary


3 Answers

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

like image 174
MR_BlueScr Avatar answered Nov 11 '22 15:11

MR_BlueScr


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.

like image 25
Vamsi Krishna Avatar answered Nov 11 '22 13:11

Vamsi Krishna


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);
    }
  }
}
like image 24
Bach Duong Avatar answered Nov 11 '22 14:11

Bach Duong