ReferenceError: localStorage is not defined

You can use standard API for localstorage, like

localStorage.setItem(key, val)

and

localStorage.getItem(key)

but If you want a angular solution for this and find a good library for localstorage, one I'm using is this

https://github.com/marcj/angular2-localstorage

also

https://www.npmjs.com/package/angular2-cool-storage

is cool to use.


The standard localStorage API should be available.

No need to declare it.

to set localStorage.setItem('name', 'storingSomething');

to get localStorage.getItem('name');


You are probably getting this error because the component is looking for localStorage when rendering server side, which is why it cannot be found and you are getting this error message.

I had a similar problem in React and solved it by simply importing the component dynamically, disabling SSR. Even just disabling SSR should be fine, you can choose whether to do this on import or export.

Hope this solves your problem

Tags:

Angular