I need to store data in the browser's session and retrieve the data until the session exits. How do you use local and session storage in Angular 2?
16 Answers
The standard localStorage
API should be available, just do e.g.:
localStorage.setItem('whatever', 'something');
It's pretty widely supported.
Note that you will need to add "dom"
to the "lib"
array in your tsconfig.json
if you don't already have it.

- 115,751
- 26
- 228
- 437
-
typescript is throwing fits for me. Did you find a way around this without having to use the npm listed for the other answers? – Winnemucca Mar 11 '17 at 11:12
-
2@Winnemucca *"throwing fits"* isn't a useful problem statement. I don't recall adding anything beyond what the Angular CLI includes. – jonrsharpe Mar 11 '17 at 20:11
-
I apologize. I had to go inside of my ts.config file to fix it. "lib": [ "es2016", "dom" ]. Did you already have "dom" added? – Winnemucca Mar 12 '17 at 16:48
-
@Winnemucca yes, that's set by the CLI. I've added it to the answer. – jonrsharpe Mar 12 '17 at 20:55
-
2localStorage.getItem('key'); localStorage.setItem('key','value'); – cbedrosian Jul 18 '17 at 22:59
How to store, retrieve & delete data from localStorage:
// General syntax for storing data
localStorage.setItem('key', 'value');
// Also note that both the key & the value has to be strings.
// So we stringify the value(if it's an object) before setting it.
// So, if you have an object that you want to save, stringify it like this
let data = {
'token': 'token',
'name': 'name'
};
localStorage.setItem('myLSkey', JSON.stringify(data));
// OR for individual key-value pairs
localStorage.setItem('myLSkey', JSON.stringify({
'token': 'token',
'name': 'name'
}));
// To retrieve the data & save it to an existing variable
data = JSON.parse(localStorage.getItem('myLSkey'));
// To remove a value/item from localStorage
localStorage.removeItem("myLSkey");
Tips:
You can also use a package for your angular app, that is based on native localStorage API (that we are using above) to achieve this and you don't have to worry about stringify and parse. Check out this package for angular 5 and above. @ngx-pwa/local-storage
You can also do a quick google search for maybe,angular local storage, & find a package that has even more Github stars etc.
Check out this page to know more about Web Storage API.

- 4,682
- 1
- 34
- 40
-
6
-
1
-
I wish i could upvote this answer more than once. I realised that as my value is a boolean, I need to stringify it in order to set the local storage value. – Yvonne Aburrow Mar 26 '19 at 15:19
-
For Angular 8, you can also check this simpler package: https://www.npmjs.com/package/@cedx/ngx-webstorage – CedX Jun 05 '19 at 20:41
Save into LocalStorage:
localStorage.setItem('key', value);
For objects with properties:
localStorage.setItem('key', JSON.stringify(object));
Get From Local Storage:
localStorage.getItem('key');
For objects:
JSON.parse(localStorage.getItem('key'));
localStorage Object will save data as string and retrieve as string. You need to Parse desired output
if value is object stored as string.
e.g. parseInt(localStorage.getItem('key'));
It is better to use framework provided localStroage instead of 3rd party library localStorageService or anything else because it reduces your project size.

- 1,546
- 18
- 19
Here is an example of a simple service, that uses localStorage to persist data:
import { Injectable } from '@angular/core';
@Injectable()
export class PersistanceService {
constructor() {}
set(key: string, data: any): void {
try {
localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
console.error('Error saving to localStorage', e);
}
}
get(key: string) {
try {
return JSON.parse(localStorage.getItem(key));
} catch (e) {
console.error('Error getting data from localStorage', e);
return null;
}
}
}
To use this services, provide it in some module in your app like normal, for example in core module. Then use like this:
import { Injectable } from '@angular/core';
@Injectable()
export class SomeOtherService {
constructor(private persister: PersistanceService) {}
someMethod() {
const myData = {foo: 'bar'};
persister.set('SOME_KEY', myData);
}
someOtherMethod() {
const myData = persister.get('SOME_KEY');
}
}

- 13,485
- 7
- 43
- 66
-
4great!, just made an example script with the same. url: https://stackblitz.com/edit/localstorage-angular-example?file=src%2Fapp%2Fapp.component.ts – sajin tm Oct 09 '18 at 23:20
Use Angular2 @LocalStorage module, which is described as:
This little Angular2/typescript decorator makes it super easy to save and restore automatically a variable state in your directive (class property) using HTML5' LocalStorage.
If you need to use cookies, you should take a look at: https://www.npmjs.com/package/angular2-cookie

- 394
- 6
- 17
-
7
-
2The successor to the angular2-cookie project is ngx-cookie https://www.npmjs.com/package/ngx-cookie – Aaron Hoffman Jun 12 '17 at 18:28
-
There is maintained and more powerful (e.g. listening for storage changes, support for cookies and temporary memory) [`ngx-store`](https://github.com/zoomsphere/ngx-store) library compatible with `angular2-localstorage` – Daniel Kucal Feb 23 '18 at 12:37
You can also consider using library maintained by me: ngx-store (npm i ngx-store
)
It makes working with localStorage, sessionStorage and cookies incredibly easy. There are a few supported methods to manipulate the data:
1) Decorator:
export class SomeComponent {
@LocalStorage() items: Array<string> = [];
addItem(item: string) {
this.items.push(item);
console.log('current items:', this.items);
// and that's all: parsing and saving is made by the lib in the background
}
}
Variables stored by decorators can be also shared across different classes - there is also @TempStorage()
(with an alias of @SharedStorage()
)) decorator designed for it.
2) Simple service methods:
export class SomeComponent {
constructor(localStorageService: LocalStorageService) {}
public saveSettings(settings: SettingsInterface) {
this.localStorageService.set('settings', settings);
}
public clearStorage() {
this.localStorageService.utility
.forEach((value, key) => console.log('clearing ', key));
this.localStorageService.clear();
}
}
3) Builder pattern:
interface ModuleSettings {
viewType?: string;
notificationsCount: number;
displayName: string;
}
class ModuleService {
constructor(public localStorageService: LocalStorageService) {}
public get settings(): NgxResource<ModuleSettings> {
return this.localStorageService
.load(`userSettings`)
.setPath(`modules`)
.setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array
.appendPath(this.moduleId)
.setDefaultValue({});
}
public saveModuleSettings(settings: ModuleSettings) {
this.settings.save(settings);
}
public updateModuleSettings(settings: Partial<ModuleSettings>) {
this.settings.update(settings);
}
}
Another important thing is you can listen for (every) storage changes, e.g. (the code below uses RxJS v5 syntax):
this.localStorageService.observe()
.filter(event => !event.isInternal)
.subscribe((event) => {
// events here are equal like would be in:
// window.addEventListener('storage', (event) => {});
// excluding sessionStorage events
// and event.type will be set to 'localStorage' (instead of 'storage')
});
WebStorageService.observe()
returns a regular Observable, so you can zip, filter, bounce them etc.
I'm always open to hearing suggestions and questions helping me to improve this library and its documentation.

- 8,684
- 6
- 39
- 64
-
-
Mainly syntax, decorators are the easiest to use, best for prototyping. Services are irreplaceable for more advanced use cases - you can update exactly what you want, so it becomes easier with complex data structures and gives better performance. – Daniel Kucal Aug 17 '18 at 08:10
-
1Thank you Daniel, perfect work. Your library helped me a lot today! :) – Michal Moravik Dec 09 '18 at 18:53
Local Storage Set Item
Syntax:
localStorage.setItem(key,value);
localStorage.getItem(key);
Example:
localStorage.setItem("name","Muthu");
if(localStorage){ //it checks browser support local storage or not
let Name=localStorage.getItem("name");
if(Name!=null){ // it checks values here or not to the variable
//do some stuff here...
}
}
also you can use
localStorage.setItem("name", JSON.stringify("Muthu"));
Session Storage Set Item
Syntax:
sessionStorage.setItem(key,value);
sessionStorage.getItem(key);
Example:
sessionStorage.setItem("name","Muthu");
if(sessionStorage){ //it checks browser support session storage/not
let Name=sessionStorage.getItem("name");
if(Name!=null){ // it checks values here or not to the variable
//do some stuff here...
}
}
also you can use
sessionStorage.setItem("name", JSON.stringify("Muthu"));
Store and Retrieve data easily

- 4,910
- 3
- 37
- 46

- 1,843
- 1
- 8
- 15
As said above, should be: localStorageService.set('key', 'value');
and localStorageService.get('key');

- 71
- 1
- 1
-
Its working for me on my angular 4 project and i want to thank to you for save my time. – Rejwanul Reja Jul 21 '17 at 04:26
-
2have not found doc about localStorageService on the api web, where i can find this? – stackdave Aug 05 '17 at 11:14
To store in LocalStorage
:
window.localStorage.setItem(key, data);
To remove an item from LocalStorage
:
window.localStorage.removeItem(key);
To get an item from LocalStorage
:
window.localStorage.getItem(key);
You can only store a string in LocalStorage
; if you have an object, first you have to convert it to string like the following:
window.localStorage.setItem(key, JSON.stringify(obj));
And when you want to get an object from LocalStorage
:
const result=JSON.parse(window.localStorage.getItem(key));
All Tips above are the same for SessionStorage
.
You can use the following service to work on SessionStorage
and LocalStorage
. All methods in the service :
getSession(key: string): any
setSession(key: string, value: any): void
removeSession(key: string): void
removeAllSessions(): void
getLocal(key: string): any
setLocal(key: string, value: any): void
removeLocal(key: string): void
removeAllLocals(): void
Inject this service in your components, services and ...; Do not forget to register the service in your core module.
import { Injectable } from '@angular/core';
@Injectable()
export class BrowserStorageService {
getSession(key: string): any {
const data = window.sessionStorage.getItem(key);
if (data) {
return JSON.parse(data);
} else {
return null;
}
}
setSession(key: string, value: any): void {
const data = value === undefined ? '' : JSON.stringify(value);
window.sessionStorage.setItem(key, data);
}
removeSession(key: string): void {
window.sessionStorage.removeItem(key);
}
removeAllSessions(): void {
for (const key in window.sessionStorage) {
if (window.sessionStorage.hasOwnProperty(key)) {
this.removeSession(key);
}
}
}
getLocal(key: string): any {
const data = window.localStorage.getItem(key);
if (data) {
return JSON.parse(data);
} else {
return null;
}
}
setLocal(key: string, value: any): void {
const data = value === undefined ? '' : JSON.stringify(value);
window.localStorage.setItem(key, data);
}
removeLocal(key: string): void {
window.localStorage.removeItem(key);
}
removeAllLocals(): void {
for (const key in window.localStorage) {
if (window.localStorage.hasOwnProperty(key)) {
this.removeLocal(key);
}
}
}
}

- 12,730
- 5
- 63
- 79
We can easily use the localStorage for setting the data and receiving the data.
Note: it works with both angular2 and angular 4
//set the data
localStorage.setItem(key, value); //syntax example
localStorage.setItem('tokenKey', response.json().token);
//get the data
localStorage.getItem('tokenKey')
//confirm if token is exist or not
return localStorage.getItem('tokenKey') != null;

- 4,910
- 3
- 37
- 46

- 475
- 8
- 22
The syntax of set item is
localStorage.setItem(key,value);
The syntax of get item is
localStorage.getItem(key);
An example of this is:
localStorage.setItem('email','abc@gmail.com');
let mail = localStorage.getItem("email");
if(mail){
console.log('your email id is', mail);
}
}
Really elegant solution are decorators. You can use them to mark variables you want to store.
export class SomeComponent {
@LocalStorage
public variableToBeStored: string;
}

- 1,011
- 10
- 12
-
Links can break. It's better to put the example directly into your answer instead. – PJvG Jan 21 '20 at 12:00
Install "angular-2-local-storage"
import { LocalStorageService } from 'angular-2-local-storage';

- 53
- 7
-
_"if you really need something to happen when something happens"_ :) from https://www.npmjs.com/package/angular-2-local-storage – Alex P. Mar 13 '18 at 09:23
-
This answer will be better if you can provide an example on how to use this LocalStorageService. – PJvG Jan 21 '20 at 12:03
You can use cyrilletuzi's LocalStorage Asynchronous Angular 2+ Service.
Install:
$ npm install --save @ngx-pwa/local-storage
Usage:
// your.service.ts
import { LocalStorage } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(private localStorage: LocalStorage) { }
}
// Syntax
this.localStorage
.setItem('user', { firstName:'Henri', lastName:'Bergson' })
.subscribe( () => {} );
this.localStorage
.getItem<User>('user')
.subscribe( (user) => { alert(user.firstName); /*should be 'Henri'*/ } );
this.localStorage
.removeItem('user')
.subscribe( () => {} );
// Simplified syntax
this.localStorage.setItemSubscribe('user', { firstName:'Henri', lastName:'Bergson' });
this.localStorage.removeItemSubscribe('user');
More info here:
https://www.npmjs.com/package/@ngx-pwa/local-storage
https://github.com/cyrilletuzi/angular-async-local-storage

- 1,840
- 18
- 13
-
-
1I suppose to deal with large amounts of data without blocking the ui – JavierFuentes Jun 11 '18 at 20:02
-
But the operation has to be done synchronously under the hood anyway, hasn't it? – Daniel Kucal Jun 11 '18 at 20:06
-
Sorry but I don't know... please, answer this to the author if you want, and let us know his response. – JavierFuentes Jun 16 '18 at 09:05
-
I think he just used the same code as for IndexedDB, which works asynchronously. – Daniel Kucal Jun 17 '18 at 09:52
-
it is possible because in my project data is written in IndexedDB by default – JavierFuentes Jun 18 '18 at 09:43
To set the item or object in local storage:
localStorage.setItem('yourKey', 'yourValue');
To get the item or object in local storage, you must remember your key.
let yourVariable = localStorage.getItem('yourKey');
To remove it from local storage:
localStorage.removeItem('yourKey');

- 31
- 1
install
npm install --save @ngx-pwa/local-storage
first of all you need to Install "angular-2-local-storage"
import { LocalStorageService } from 'angular-2-local-storage';
Save into LocalStorage:
localStorage.setItem('key', value);
Get From Local Storage:
localStorage.getItem('key');

- 417
- 4
- 12