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

3 answers

To preserve the state data after updating the application, you can use localStorage

or sessionStorage


  1. 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 data

    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.

  2. 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 a httpOnly

    flag httpOnly

    , 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.

  1. Is CSRF token required when using stateless (sessionless) authentication? Check the accepted answer and others.



  4. This will let you know the pitfalls and instructions for using localStorage.



  • 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:

  • 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.



You can cache your state in sessionStorage

, which will survive page (tab) refresh events, but will be cleared when the page or browser is closed.

SessionStorage docs



All Articles