i am using Nuxt.js for SSR. I have a login system whenever i Log in my App, i get an JSON web token (JWT) and store it in my Localstorage.
The problem is now the SSR. Whenever i try to access the Localstorage it says its not defined. I found an Stackoverflow article about this problem, its because the Code is server side rendered so it has no access to the Localstorage.
I tried the created()
lifecycle hook to check if token exist in localstorage, no success.
I also tried with nuxtServerInit
also no success.
How can i check if token exist in localstorage on the client side or is there any better idea?
i am using Nuxt.js for SSR. I have a login system whenever i Log in my App, i get an JSON web token (JWT) and store it in my Localstorage.
The problem is now the SSR. Whenever i try to access the Localstorage it says its not defined. I found an Stackoverflow article about this problem, its because the Code is server side rendered so it has no access to the Localstorage.
I tried the created()
lifecycle hook to check if token exist in localstorage, no success.
I also tried with nuxtServerInit
also no success.
How can i check if token exist in localstorage on the client side or is there any better idea?
Share Improve this question asked Oct 22, 2019 at 10:31 ilijanovicilijanovic 731 gold badge1 silver badge3 bronze badges 5- To check if the localstorage really exist. Press f12 and go to application tab and you will see there the Local Storage. It will show you the site,key and value. Btw, how did you use local storage? – Renato Manalili Commented Oct 22, 2019 at 10:33
- 1 Server side code can't see Javascript localstorage directly, you will need the client to send this somehow, either cookie / ajax / websocket etc, or even a form post. – Keith Commented Oct 22, 2019 at 10:35
- @RenatoManalili thats not the problem, whenever i login, i retrieve a jwt from the backend and save it in my localstorage. and i know how to check if it exist, the problem is that nuxtjs is serverside rendered so it has no access to localstorage. i wanna check if the token exist on pageload – ilijanovic Commented Oct 22, 2019 at 10:35
- @ilijanovic oh I see, much better if you will use vuex. – Renato Manalili Commented Oct 22, 2019 at 10:40
- @RenatoManalili i use vuex, after every refresh the storage is refreshed so i need to login again after every page refresh. right now i am using vuex and want to improve the app – ilijanovic Commented Oct 22, 2019 at 10:44
1 Answer
Reset to default 5You may call a function on mounted
export default {
mounted() {
this.storage();
},
methods:{
storage(){
localStorage.getItem("authToken");
}
}
}
OR use created
alongwith process.browser
check
export default {
created() {
this.storage();
},
methods:{
storage(){
if (process.browser){
localStorage.getItem("authToken");
}
}
}
}