blog > creating-a-generic-session-storage-implementation-in-angular

Creating a generic session storage implementation in Angular

by Yashlin Naidoo
Published on: 10/26/2023

Creating a generic session storage mechanism in Angular

Managing data between page reloads and user interactions is a common challenge. One powerful solution to this problem is the use of browser storage mechanisms like session storage. However, working with session storage can be a complex task, especially when it involves handling different types of data.

By creating a generic session storage handler service, we can standardize access to the browser API’s for session storage and thus manage the session data more consistently

Let’s start by running the cli command to generate a service for us. This service will act as a container for our session storage implementation and all its utility functions.

ng generate service sessionStorage

Once our service is created lets add some of these utility functions and methods to store data into session storage via the browser session storage API.

import { Injectable } from '@angular/core';

  providedIn: 'root'
export class SessionStorageService {

  constructor() { }

  getItem(key: string) {
    try {
      const result = JSON.parse(sessionStorage.getItem(key) || '{}');
      return result;

    } catch (error: any) {

  setItem(key: string, value: string | any) {
    try {
      return sessionStorage.setItem(key, JSON.stringify(value));
    } catch (error) {

  removeItem(key: string) {
    try {
      return sessionStorage.removeItem(key);
    } catch (error) {


  clearEntireSession() {


Lets break down these utility functions and how they work

  • getItem(key: string): Retrieves data from sessionStorage based on the provided key and returns it in a structured format. If there’s an error parsing the data, it logs the error to the console.
  • setItem(key: string, value: string | any): Stores data in sessionStorage under the specified key. It serializes the data to JSON format before storage. If an error occurs during storage, it logs the error.
  • removeItem(key: string): Removes data from sessionStorage based on the provided key. If an error occurs during removal, it logs the error.
  • clearEntireSession(): Clears the entire sessionStorage, effectively removing all stored data. This function is useful when you want to reset or clear all network request and response data

Examples of how to use this service

  1. User Authentication State: You can use this service to store and manage user authentication state in your Angular application. When a user logs in, you can use setItem to store their authentication token or user object in sessionStorage. When the user logs out, you can call removeItem to clear the stored authentication data.
    // When user logs in const user = { id: 123, username: 'example_user' }; sessionStorageService.setItem('user', user); // When user logs out sessionStorageService.removeItem('user');
  2. Shopping Cart: If your application has a shopping cart feature, you can use sessionStorage to store the user’s cart items temporarily. This way, the cart items will persist across page reloads until the user completes the purchase or logs out.
    // Add item to the cart 
    const cartItem = { productId: 456, quantity: 2 }; 
    const currentCart = sessionStorageService.getItem('cart') || []; currentCart.push(cartItem); sessionStorageService.setItem('cart', currentCart); 
    // Retrieve and display the cart 
    const userCart = sessionStorageService.getItem('cart');
  3. Form Data Persistence: When a user fills out a lengthy form but accidentally navigates away from the page, you can use sessionStorage to store the form data temporarily. This way, you can retrieve and populate the form with the saved data when the user returns.
    // Save form data const formData = { name: 'John', email: '' }; sessionStorageService.setItem('formData', formData); // Retrieve and populate the form const savedFormData = sessionStorageService.getItem('formData');
  4. Error Handling and Logging: You can use this service to log errors and debugging information. For example, when an unexpected error occurs, you can log the error details to sessionStorage for later analysis.
    try { // Code that may throw an error } 
    catch (error) { 
    const errorDetails = { message: error.message, stack: error.stack, timestamp: new Date().toISOString(), }; sessionStorageService.setItem('errorLog', errorDetails); } 
    // Retrieve and review error logs 
    const errorLog = sessionStorageService.getItem('errorLog');
  5. Session Management: The clearEntireSession function is useful for managing the user’s session data. For example, when a user logs out or their session expires, you can call this function to clear all session-related data. // When the user logs out or the session expires sessionStorageService.clearEntireSession();
  6. Conclusion

    In conclusion, we have created a generic session storage service in Angular that provides a convenient and reusable way to interact with the browser’s session storage. This service offers a set of functions for storing, retrieving, and managing data in session storage.

    Overall, the SessionStorageService simplifies session storage interactions in Angular, promotes code reusability, and enhances error handling, making it a valuable addition to your application for managing temporary data across user sessions.


Yashlin Naidoo

Location Icon
Cascades Office Park, Wasbank St,
Little Falls,
Roodepoort, 1724,
Gauteng, South Africa
Runninghill Logo
Stay connected
LinkedinX platformFacebook