Skip to main content

Session Storage Utilities

Convenient utilities to safely interact with the browser's Session Storage API. Store, retrieve, and remove typed items for per-tab and per-session persistence with custom serialization support.


Import

import { getFromSessionStorage, saveToSessionStorage, removeFromSessionStorage } from 'nhb-toolbox';

getFromSessionStorage

Type-safe getter for items stored in session storage with custom deserialization support.

function getFromSessionStorage<T>(key: string, deserialize?: Deserializer<T>): T | null

Usage Examples

// Given: sessionStorage.setItem('color', JSON.stringify('blue'))
const color = getFromSessionStorage<string>('color');
// Returns: 'blue'

Parameters

NameTypeDescription
keystringThe key for the session storage item.
deserializeDeserializer<T>Optional function to convert stored string back to type T. Defaults to JSON.parse.

Returns

  • The parsed value (T) if it exists and can be parsed.
  • null if the key does not exist or parsing fails.

saveToSessionStorage

Stores values in session storage with custom serialization support.

function saveToSessionStorage<T>(key: string, value: T, serialize?: Serializer<T>): void

Usage Examples

saveToSessionStorage('count', 10);
// sessionStorage entry: { count: "10" }

Parameters

NameTypeDescription
keystringThe key under which to store the value.
valueTThe value to store.
serializeSerializer<T>Optional function to convert value to string. Defaults to JSON.stringify.

removeFromSessionStorage

Removes an item from session storage.

function removeFromSessionStorage(key: string): void

Usage Example

removeFromSessionStorage('cart');
// Removes 'cart' from session storage. No effect if not found.

Parameters

NameTypeDescription
keystringThe key to remove from session storage.

Advanced Serialization Examples

Authentication Session Data

interface AuthSession {
accessToken: string;
refreshToken: string;
expiresAt: Date;
scopes: Set<string>;
}

// Save authentication data
saveToSessionStorage<AuthSession>(
'auth',
authData,
(value) => JSON.stringify({
...value,
expiresAt: value.expiresAt.toISOString(),
scopes: [...value.scopes].join(','),
})
);

// Retrieve with proper type reconstruction
const session = getFromSessionStorage<AuthSession>(
'auth',
(value) => {
const parsed = JSON.parse(value);

return {
...parsed,
expiresAt: new Date(parsed.expiresAt),
scopes: new Set(parsed.scopes.split(',')),
};
}
);

Form Wizard State

// Multi-step form with progress tracking
saveToSessionStorage(
'signup-wizard',
{
currentStep: 2,
completedSteps: [1, 2],
userData: { name: 'John', email: 'john@example.com' },
startedAt: new Date()
},
(value) => JSON.stringify({
...value,
startedAt: value.startedAt.toISOString()
})
);

Key Features

  1. Type Safety: You get the right type back, thanks to generic inference.
  2. Flexible Serialization: Support for custom serialization and deserialization functions.
  3. Consistent JSON Handling: Storage is always as stringified JSON with sensible defaults.
  4. Per-Tab Session: Data is unique per browser tab or window session.
  5. Error Handling: Gracefully handles common storage errors with console warnings.
  6. Simple and Fast: Easy, one-liner API for all value types.

Limitations

  1. Session Scope: Data persists only until the tab or window is closed.
  2. Storage Limits: Subject to browser storage quotas (typically 5-10MB).
  3. Browser Only: Not available server-side, and may be disabled in some contexts (incognito, etc).
  4. Synchronous: All operations are synchronous and may block the main thread with large data.

Best Practices

  • Use custom serialization for complex objects containing Dates, Maps, Sets, or other non-JSON-native types.
  • Clear sensitive session data on logout or when no longer needed.
  • For large datasets, consider compression or alternative storage solutions.
  • Always use matching serialization/deserialization functions for consistent data handling.
  • Storing tab-specific state (temporary settings, form progress, etc.)
  • Multi-step workflows, cart/session caching
  • UI state, selections, or navigation history per session/tab
  • Authentication tokens and temporary user sessions
  • Unsaved form data and draft content

See Also