Vuex keeps empty if I refresh my page
How do I save my store if I refresh the web page?
let store = new Vuex.Store( {
modules: {
demo, auth
},
strict: true
} );
let router = new VueRouter( {
mode: 'history',
saveScrollPosition: true,
routes: routes
} )
I am using history mode, but if I reload my webpage my store is empty. There is a solution?
source to share
To preserve the state data after updating the application, you can use localStorage
or sessionStorage
.
-
XSS: Problems with storing tokens in,
localStorage
as you say,localStorage
the fact that the application is vulnerable to XSS (cross-site scripting) attacks. Plus, it's pretty safe.localStorage
is tied to a domain, so the datawww.yourapp.com
will remain there even after you close your browser, unlike cookies, you will not need to control which site made the request. All tabs in a browser with the same domain will be able to use the data inlocalStorage
If the specified behavior is not required you can go to
sessionStorage
, it works pretty much the same, but the data is cleared when you close the browser. -
As far as cookies go, make sure they help keep your token picked up by XSS, but then you will need to make sure you also provide
csrf-token
to protect against CSRF (Cross Site Request Forgery) attacks.If you plan on using cookies, make sure
httpOnly
they have ahttpOnly
flaghttpOnly
, otherwise they are useless.
Overall, I saw that localStorage was a very recommended solution for maintaining tokens and other application data.
I'll add sources to this answer for reference.
-
Is CSRF token required when using stateless (sessionless) authentication? Check the accepted answer and others.
-
https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/HTML5_Security_Cheat_Sheet.md
-
https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage
-
https://www.whitehatsec.com/blog/web-storage-security/ This will let you know the pitfalls and instructions for using localStorage.
source to share
-
If you refresh the page (F5), you start your application again, so if you don't initialize the store with some data, it will be empty as soon as the application starts.
-
You can decide what states you want to store in this case and store them in cookie / LocalStorage and then
app.js
load them from cookie / LocalStorage into storage. This is common practice for things like authentication token, etc., since you want the user to log in when the page is refreshed. Good post from Stormpath about storing tokens: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage -
If the Vuex store and the entire app are reloaded when switching from route to route - something is wrong with your application, you may be using the VueRouter navigation incorrectly.
source to share