Nuxt.js: How do I use local Storage?

Created on 4 Jun 2017  路  6Comments  路  Source: nuxt/nuxt.js

I think javaScript can't find localStorage because it is looking for it on Server Side. I am trying to use a plugin for vuex to save data on localStorage.

Can anyone help me set it up? Getting error: localStorage is not defined.

This question is available on Nuxt.js community (#c716)

Most helpful comment

Yeah, I mean if I want to use it? If it is always process.server, then it seems I can't use it?

All 6 comments

HI @andrisole92

You should check if (process.server) before trying to use the localStorage since it does not exist on server-side.

Yeah, I mean if I want to use it? If it is always process.server, then it seems I can't use it?

Yes, obviously

You could say

import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersist from 'vuex-persist'

Vue.use(Vuex)
let vuexLocalStorage = null;

if (process.browser) {
    vuexLocalStorage = new VuexPersist({
      key: 'vuex', // The key to store the state on in the storage provider.
      storage: window.localStorage, // or window.sessionStorage or localForage
    })
}
export function createStore() {
    return new Vuex.Store({
        state: {
            ...
        },
        actions: {...},
        mutations: {...},
        getters: {...},
        plugins: process.browser ? [vuexLocalStorage.plugin] : []
    })
}

I hope this helps

@jalasem Ok this is old but in my case process.browser to use with window.localStorage doesn't seem to work.

I'm using a middleware to store my options, and here is what I thought of doing.

if (process.browser) {
  window.localStorage.set('options', JSON.stringify(options));
}

But the localStorage doesn't set after auth is passed, and that's because process.browser is always false. Any ideas?

Use cookies, it's available both in browser and server as well

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

msudgh picture msudgh  路  3Comments

VincentLoy picture VincentLoy  路  3Comments

gary149 picture gary149  路  3Comments

vadimsg picture vadimsg  路  3Comments

bimohxh picture bimohxh  路  3Comments