Local Storage
The LocalStorage service is a custom drop-in replacement for the browser’s localStorage that works seamlessly in both browser and server environments. It is fully compatible with Angular SSR by using TransferState to transfer storage values from the server to the client during server-side rendering.
Overview
Applications often depend on localStorage to store preferences like themes, layout states, and onboarding steps. However, direct access to localStorage will fail during server rendering. This implementation avoids runtime errors and ensures that storage data is preserved and hydrated between server and client.
- SSR Compatible
- Works on both server and browser using
TransferStateto preserve data during SSR hydration. - Safe Fallback
- Replaces direct access to
localStoragewith a Map-based storage on the server. - Identical API
- Mimics the native
StorageAPI.
Provider Setup
To enable local storage utilities, add the provideLocalStorage function to your application configuration:
import { provideLocalStorage } from '@/app/core/local-storage';
export const appConfig: ApplicationConfig = {
providers: [
provideLocalStorage(),
// ...other providers
],
};Usage
const storage = inject(LocalStorage);
storage.setItem('theme', 'dark');
const theme = storage.getItem('theme');How It Works
- On the server, the class stores all keys in a Map object.
- When
setItem()is called, the values are recorded in memory and injected into Angular’sTransferStateservice. - On the client, the service reads the state back from the transfer store and initializes
localStorageso the data is already present before hydration completes.
This allows SSR-safe reads and writes while still taking advantage of persistent client storage during runtime.
When to Use
- Use this service when storing UI preferences, session metadata, onboarding progress, or any non-sensitive, client-persisted information.
- Use this in place of
localStorageanywhere in your Angular application that runs in a universal environment.