getAllLocalStorageItems
Returns all key-value pairs from localStorage.
1/**
2 * Returns all key-value pairs from localStorage.
3 *
4 * @returns An object where keys are localStorage keys and values are parsed if possible.
5 */
6export function getAllLocalStorageItems(): Record<string, any> {
7 const result: Record<string, any> = {};
8
9 for (let i = 0; i < localStorage.length; i++) {
10 const key = localStorage.key(i);
11 if (key === null) continue;
12
13 const item = localStorage.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
Retrieves the full contents of localStorage in a single pass, ideal for diagnostics or state backups.
Safe Parsing Strategy
Attempts to parse JSON-encoded values while gracefully falling back to raw strings if parsing fails.
Key Preservation
Maintains original localStorage keys, making the output predictable and easy to map back.
Zero Dependencies
Uses only native browser APIs — no need for additional libraries or wrappers.
Flexible Output Format
Returns a plain JavaScript object, allowing seamless integration with logging, inspection, or further processing.
Tests | Examples
1beforeEach(() => {
2 localStorage.clear();
3});
4
5test('returns empty object when localStorage is empty', () => {
6 expect(getAllLocalStorageItems()).toEqual({});
7});
8
9test('returns all key-value pairs with parsed values', () => {
10 localStorage.setItem('num', JSON.stringify(1));
11 localStorage.setItem('str', JSON.stringify('test'));
12 localStorage.setItem('obj', JSON.stringify({ x: true }));
13
14 const items = getAllLocalStorageItems();
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 localStorage.setItem('bad', 'notjson');
25
26 const items = getAllLocalStorageItems();
27
28 expect(items.bad).toBe('notjson');
29});
Common Use Cases
Debugging Application State
Inspect all localStorage entries at once during development or bug analysis.
Exporting User Data
Bundle all localStorage items into a downloadable file or send to a server for backup.
Session Persistence Check
Verify presence and structure of session-related data on page load or after errors.
Data Migration or Cleanup
Analyze all keys to selectively remove or transform legacy values.
Admin Tools or Dev Panels
Power developer UIs that display localStorage contents in real-time for inspection.