Introduction

Local storage is a web storage feature in modern browsers that allows storing data persistently in a key-value format. Angular applications use local storage to retain user-specific data even after page reloads or session ends.

Why Use Local Storage in Angular?

  1. Persistence: Stores data across browser sessions.
  2. Performance: Faster access compared to API calls.
  3. Offline Availability: Works without an internet connection.
  4. Simple Key-Value Storage: Easy to use and implement.
  5. Storage Limitations: Local storage has a maximum limit of 5MB per origin.

When to Use Angular Local Storage?

  1. User Preferences: Store theme settings, language preferences, etc.
  2. Session Data: Retain user login state (not recommended for sensitive data).
  3. Temporary Cache: Store API response for faster access.
  4. Form Auto-Save: Preserve form inputs temporarily.

How to Use Local Storage in Angular

Angular does not provide a built-in local storage service. However, you can use the window.localStorage API or third-party libraries like ngx-webstorage or angular-web-storage.

Using window.localStorage

Storing Data
localStorage.setItem('username', 'JohnDoe');

Retrieving Data
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe

Removing Data
localStorage.removeItem('username');

Clearing All Data
localStorage.clear();

Using a Service to Handle Local Storage

It’s a good practice to create a reusable service for local storage operations.

local-storage.service.ts

export class LocalStorageService {
  private secretKey = 'your-secret-key';

  setItem(key: string, value: any): void {
    localStorage.setItem(key, JSON.stringify(value));
  }
  
  getItem(key: string): any {
    const data = localStorage.getItem(key);
    return data ? JSON.parse(data) : null;
  }
  
  setEncryptedItem(key: string, value: any): void {
    const encryptedValue = CryptoJS.AES.encrypt(JSON.stringify(value), this.secretKey).toString();
    localStorage.setItem(key, encryptedValue);
  }
  
  getDecryptedItem(key: string): any {
    const encryptedData = localStorage.getItem(key);
    if (!encryptedData) return null;
    const bytes = CryptoJS.AES.decrypt(encryptedData, this.secretKey);
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
  }
  
  removeItem(key: string): void {
    localStorage.removeItem(key);
  }
  
  clear(): void {
    localStorage.clear();
  }
}

Using the Service in a Component

import { Component } from '@angular/core';
import { LocalStorageService } from './local-storage.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  constructor(private localStorageService: LocalStorageService) {
    
    this.localStorageService.setItem('username', 'JohnDoe');
    console.log(this.localStorageService.getItem('username'));
    
    this.localStorageService.setEncryptedItem('secureData', 'Sensitive Info');
      console.log(this.localStorageService.getDecryptedItem('secureData'));
  }
}

Why Store Data in Encrypted Format?

  1. Security: Prevents unauthorized access to sensitive data.
  2. Data Integrity: Ensures data is not tampered with.
  3. Compliance: Meets data protection regulations like GDPR.
  4. User Privacy: Safeguards user information from being stolen.
  5. Protection from XSS Attacks: Even if an attacker gains access to local storage data, encrypted data remains unreadable.

Using Third-Party Libraries

ngx-webstorage

Install using:
npm install ngx-webstorage

Usage

Modify app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NgxWebstorageModule } from 'ngx-webstorage';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, NgxWebstorageModule.forRoot()],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Using in a Component

import { Component } from '@angular/core';
import { LocalStorageService } from 'ngx-webstorage';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  constructor(private localStorage: LocalStorageService) {
    this.localStorage.store('username', 'JohnDoe');
    console.log(this.localStorage.retrieve('username'));
  }
}

Security Concerns

  1. Avoid storing sensitive data like passwords and tokens.
  2. Use encryption if storing sensitive information is necessary.
  3. Set expiration strategies using timestamps.
  4. Storage Limitations: Local storage has a 5MB limit per origin. Avoid storing large datasets.
  5. Cross-Site Scripting (XSS) Protection: Encrypted data prevents attackers from easily reading stored values.

Conclusion

Local storage is a powerful and simple tool for storing small amounts of data in an Angular application. For better maintainability, use a service approach or third-party libraries for more advanced functionality.

Need Help With Angular Development?

Work with our skilled Angular developers to accelerate your project and boost its performance.

Hire Angular Developers

Support On Demand!

Related Q&A