Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Storage Utilities in JavaScript

Build storage utility classes in JavaScript: a JSON helper, expiring items, namespaced keys and an XOR encoding demo, with explanation and output.

IntermediateJavaScript LocalStorage and SessionStorageExample 6 of 10

Run this in the browser console or a page script. localStorage and sessionStorage are browser features, so plain Node will not have them.

storage-utilities.js
1// Method 1: Storage helper class
2class StorageUtil {
3 constructor(storage = localStorage) {
4 this.storage = storage;
5 }
6
7 set(key, value) {
8 try {
9 this.storage.setItem(key, JSON.stringify(value));
10 return true;
11 } catch (e) {
12 console.error('Storage error:', e);
13 return false;
14 }
15 }
16
17 get(key, defaultValue = null) {
18 try {
19 const item = this.storage.getItem(key);
20 return item ? JSON.parse(item) : defaultValue;
21 } catch (e) {
22 console.error('Parse error:', e);
23 return defaultValue;
24 }
25 }
26
27 remove(key) {
28 this.storage.removeItem(key);
29 }
30
31 clear() {
32 this.storage.clear();
33 }
34
35 has(key) {
36 return this.storage.getItem(key) !== null;
37 }
38
39 keys() {
40 return Object.keys(this.storage);
41 }
42
43 size() {
44 let total = 0;
45 for (let key in this.storage) {
46 if (this.storage.hasOwnProperty(key)) {
47 total += this.storage[key].length + key.length;
48 }
49 }
50 return total;
51 }
52}
53
54const storage = new StorageUtil();
55storage.set('name', 'John');
56console.log('Name:', storage.get('name'));
57console.log('Has name:', storage.has('name'));
58console.log('Keys:', storage.keys());
59
60// Method 2: Storage with expiration
61class ExpiringStorage {
62 set(key, value, ttl) {
63 const item = {
64 value: value,
65 expiry: Date.now() + ttl
66 };
67 localStorage.setItem(key, JSON.stringify(item));
68 }
69
70 get(key) {
71 const itemStr = localStorage.getItem(key);
72 if (!itemStr) return null;
73
74 const item = JSON.parse(itemStr);
75 if (Date.now() > item.expiry) {
76 localStorage.removeItem(key);
77 return null;
78 }
79
80 return item.value;
81 }
82
83 clearExpired() {
84 const now = Date.now();
85 for (let i = localStorage.length - 1; i >= 0; i--) {
86 const key = localStorage.key(i);
87 const itemStr = localStorage.getItem(key);
88 try {
89 const item = JSON.parse(itemStr);
90 if (item.expiry && now > item.expiry) {
91 localStorage.removeItem(key);
92 }
93 } catch (e) {
94 // Not an expiring item, skip
95 }
96 }
97 }
98}
99
100const expiringStorage = new ExpiringStorage();
101expiringStorage.set('token', 'abc123', 3600000); // 1 hour
102console.log('Token:', expiringStorage.get('token'));
103
104// Method 3: Namespaced storage
105class NamespacedStorage {
106 constructor(namespace) {
107 this.namespace = namespace + ':';
108 }
109
110 set(key, value) {
111 localStorage.setItem(this.namespace + key, JSON.stringify(value));
112 }
113
114 get(key, defaultValue = null) {
115 const item = localStorage.getItem(this.namespace + key);
116 return item ? JSON.parse(item) : defaultValue;
117 }
118
119 remove(key) {
120 localStorage.removeItem(this.namespace + key);
121 }
122
123 clear() {
124 const keys = Object.keys(localStorage);
125 keys.forEach(key => {
126 if (key.startsWith(this.namespace)) {
127 localStorage.removeItem(key);
128 }
129 });
130 }
131
132 getAll() {
133 const items = {};
134 const keys = Object.keys(localStorage);
135 keys.forEach(key => {
136 if (key.startsWith(this.namespace)) {
137 const itemKey = key.replace(this.namespace, '');
138 items[itemKey] = JSON.parse(localStorage.getItem(key));
139 }
140 });
141 return items;
142 }
143}
144
145const userStorage = new NamespacedStorage('user');
146userStorage.set('name', 'John');
147userStorage.set('email', 'john@example.com');
148console.log('All user data:', userStorage.getAll());
149
150// Method 4: Storage with encryption (simple)
151class EncryptedStorage {
152 constructor(secret) {
153 this.secret = secret;
154 }
155
156 encrypt(text) {
157 // Simple XOR encryption (not secure, for demo only)
158 let result = '';
159 for (let i = 0; i < text.length; i++) {
160 result += String.fromCharCode(text.charCodeAt(i) ^ this.secret.charCodeAt(i % this.secret.length));
161 }
162 return btoa(result); // Base64 encode
163 }
164
165 decrypt(encrypted) {
166 const text = atob(encrypted);
167 let result = '';
168 for (let i = 0; i < text.length; i++) {
169 result += String.fromCharCode(text.charCodeAt(i) ^ this.secret.charCodeAt(i % this.secret.length));
170 }
171 return result;
172 }
173
174 set(key, value) {
175 const encrypted = this.encrypt(JSON.stringify(value));
176 localStorage.setItem(key, encrypted);
177 }
178
179 get(key, defaultValue = null) {
180 const encrypted = localStorage.getItem(key);
181 if (!encrypted) return defaultValue;
182 try {
183 return JSON.parse(this.decrypt(encrypted));
184 } catch (e) {
185 return defaultValue;
186 }
187 }
188}
189
190const secureStorage = new EncryptedStorage('mySecretKey');
191secureStorage.set('password', 'secret123');
192console.log('Password:', secureStorage.get('password'));

Sample Output

Name: John
Has name: true
Keys: ["name"]
Token: abc123
All user data: { name: 'John', email: 'john@example.com' }
Password: secret123

In this one

  • How a wrapper class removes repeated storage code
  • How to add expiry to stored items
  • How namespaced keys avoid collisions
  • Why XOR plus Base64 is not real encryption

How it works

  1. 1

    StorageUtil saves name and reads it, checks it and lists keys.

  2. 2

    ExpiringStorage saves a token for one hour and reads it.

  3. 3

    NamespacedStorage saves user:name and user:email and returns both.

  4. 4

    EncryptedStorage encodes and decodes a password.

Edge cases

Keys list shows other data

storage.keys() includes every key on the site.

The output shows only name on a clean origin. A real site may show more.

Namespace prefix inside a key

key.replace(this.namespace, '') only removes the first match.

That is the intended part, but avoid putting the prefix text inside key names.

Non-ASCII text in EncryptedStorage

btoa throws on characters outside Latin-1.

Encode with TextEncoder first if you need full Unicode.

What's going on

Calling localStorage directly everywhere leads to repeated code: stringify, parse, try/catch, defaults. Utility classes wrap that logic once. They handle errors, give defaults, and add features like expiry, namespaces and encoding.

Method 1 is StorageUtil. Its constructor takes a storage object and defaults to localStorage, so the same class works with sessionStorage too. set saves JSON. get parses it and returns a default on error. has checks if a key exists. getItem returns null for missing keys, so has compares with !== null. keys lists all keys. size adds up key and value lengths.

Method 2 is ExpiringStorage. It saves { value, expiry }. get returns null and deletes the item if the time has passed. clearExpired walks backwards through all keys and removes expired ones. Items that are not JSON are skipped in the catch block.

Method 3 is NamespacedStorage. A namespace is a prefix that groups keys, like "user:name" and "user:email". It stops different parts of an app, or different apps on the same domain, from overwriting each other. clear only removes keys with that prefix, and getAll returns them as one object.

Method 4 is EncryptedStorage. It mixes each character with a secret key using XOR, then encodes with btoa, which turns text into Base64. Base64 is a safe text format. This hides the value from a quick glance, but it is not real security. The secret is in the page code, so anyone can reverse it. Never store real passwords in browser storage.

Use cases are app configuration, user preferences, cached data and session management. Best practices: use classes for organisation, handle errors gracefully, provide defaults, and add only features you need.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does a namespace like "user:" prevent?

Pick an answer to check it.

Question 2

Is XOR + Base64 strong encryption?

Pick an answer to check it.

Questions people ask

Can StorageUtil use sessionStorage?

Yes. new StorageUtil(sessionStorage).

Is EncryptedStorage safe for passwords?

No. It is a demo. Anyone with the page code can decode it.

Why walk keys backwards in clearExpired?

Removing an item shifts the positions of later keys.