getAllSessionStorageItems
Returns all key-value pairs from sessionStorage.
1/**
2 * Returns all key-value pairs from sessionStorage.
3 *
4 * @returns An object where keys are sessionStorage keys and values are parsed if possible.
5 */
6export function getAllSessionStorageItems(): Record<string, any> {
7 const result: Record<string, any> = {};
8
9 for (let i = 0; i < sessionStorage.length; i++) {
10 const key = sessionStorage.key(i);
11 if (key === null) continue;
12
13 const item = sessionStorage.getItem(key);
14 try {
15 result[key] = JSON.parse(item!);
16 } catch {
17 result[key] = item;
18 }
19 }
20
21 return result;
22}
Comprehensive Snapshot
Provides a complete object-based representation of all sessionStorage entries at once, which is useful for debugging or state inspection.
Graceful Parsing
Automatically parses JSON when possible while preserving raw strings if parsing fails - ensuring no data is lost.
Safe and Defensive
Includes null checks and fallback behavior, preventing runtime crashes from malformed data or unexpected nulls.
Utility for Debugging & Export
Great for exporting session data during development or testing phases to understand session behavior.
Tests | Examples
1beforeEach(() => {
2 sessionStorage.clear();
3});
4
5test('returns empty object when sessionStorage is empty', () => {
6 expect(getAllSessionStorageItems()).toEqual({});
7});
8
9test('returns all key-value pairs with parsed values', () => {
10 sessionStorage.setItem('num', JSON.stringify(1));
11 sessionStorage.setItem('str', JSON.stringify('test'));
12 sessionStorage.setItem('obj', JSON.stringify({ x: true }));
13
14 const items = getAllSessionStorageItems();
15
16 expect(items).toEqual({
17 num: 1,
18 str: 'test',
19 obj: { x: true },
20 });
21});
22
23test('returns raw string if JSON.parse fails', () => {
24 sessionStorage.setItem('bad', 'notjson');
25
26 const items = getAllSessionStorageItems();
27
28 expect(items.bad).toBe('notjson');
29});
Common Use Cases
Session State Dumping
Quickly inspect or log all session data for debugging, analytics, or support purposes.
Data Migration or Sync
Read all session data to migrate it into another store like localStorage or an API payload.
Backup and Restore
Temporarily store or restore sessionStorage data across page reloads or tabs.
Dev Tools Integration
Enable in-browser tools to display session data in a structured and readable format.