0
# Storage & Configuration
1
2
Store.js provides multiple build configurations and storage backends to optimize for different browser support requirements and use cases.
3
4
## Capabilities
5
6
### Build Configurations
7
8
#### Legacy Build
9
10
Maximum browser compatibility including IE6+ and ancient Firefox versions.
11
12
```javascript { .api }
13
// Main package entry point (package.json "main" field)
14
var store = require('store')
15
// Equivalent to:
16
var store = require('store/dist/store.legacy')
17
```
18
19
**Features:**
20
- All storage backends for maximum fallback support
21
- JSON2 plugin for legacy browser JSON support
22
- Works in IE6+, old Firefox, and all modern browsers
23
- Larger bundle size (~13KB minified)
24
25
**Usage Examples:**
26
27
```javascript
28
var store = require('store')
29
30
// Works even in IE6
31
store.set('data', { message: 'Hello IE6!' })
32
var data = store.get('data')
33
console.log(data.message) // 'Hello IE6!'
34
```
35
36
#### Modern Build
37
38
Optimized for modern browsers with smaller bundle size.
39
40
```javascript { .api }
41
// Modern build for current browsers
42
var store = require('store/dist/store.modern')
43
```
44
45
**Features:**
46
- Modern storage backends only (localStorage, sessionStorage, cookieStorage, memoryStorage)
47
- No legacy browser support code
48
- Smaller bundle size (~7KB minified)
49
- Works in all browsers from IE8+
50
51
**Usage Examples:**
52
53
```javascript
54
var store = require('store/dist/store.modern')
55
56
// Same API, smaller bundle
57
store.set('user', { name: 'Alice', preferences: { theme: 'dark' } })
58
console.log(store.get('user').name) // 'Alice'
59
```
60
61
#### Everything Build
62
63
All features and plugins included in one bundle.
64
65
```javascript { .api }
66
// Complete build with all plugins
67
var store = require('store/dist/store.everything')
68
```
69
70
**Features:**
71
- All storage backends
72
- All plugins pre-loaded
73
- Largest bundle size (~22KB minified)
74
- Maximum functionality out of the box
75
76
**Usage Examples:**
77
78
```javascript
79
var store = require('store/dist/store.everything')
80
81
// All plugin methods available immediately
82
store.set('temp', 'data', Date.now() + 60000) // expire plugin
83
store.watch('temp', function(newVal, oldVal) { // events plugin
84
console.log('Temp data changed')
85
})
86
store.push('items', 'new item') // operations plugin
87
```
88
89
#### V1 Backcompat Build
90
91
Complete backwards compatibility with store.js version 1.x API.
92
93
```javascript { .api }
94
// V1 compatibility build
95
var store = require('store/dist/store.v1-backcompat')
96
```
97
98
**Features:**
99
- All storage backends for maximum compatibility
100
- V1 backcompat plugin pre-loaded
101
- JSON2 plugin for legacy browser support
102
- Dump plugin for getAll() functionality
103
- All v1.x methods available (has, transact, clear, forEach, etc.)
104
- Medium bundle size (~15KB minified)
105
106
**Usage Examples:**
107
108
```javascript
109
var store = require('store/dist/store.v1-backcompat')
110
111
// V1 API works out of the box
112
if (store.has('user')) {
113
var user = store.get('user')
114
}
115
116
store.transact('visits', 0, function(current) {
117
return current + 1
118
})
119
120
store.forEach(function(key, value) {
121
console.log(key, value)
122
})
123
```
124
125
### Custom Store Creation
126
127
#### Store Engine
128
129
Core factory for creating custom store instances.
130
131
```javascript { .api }
132
/**
133
* Create custom store with specific storages and plugins
134
* @param {Array|Object} storages - Storage backend(s) to use
135
* @param {Array|Function} plugins - Plugin(s) to apply
136
* @param {string} [namespace] - Optional namespace
137
* @returns {Object} Custom store instance
138
*/
139
var engine = require('store/src/store-engine')
140
var customStore = engine.createStore(storages, plugins, namespace?)
141
```
142
143
**Usage Examples:**
144
145
```javascript
146
var engine = require('store/src/store-engine')
147
var localStorage = require('store/storages/localStorage')
148
var memoryStorage = require('store/storages/memoryStorage')
149
var expirePlugin = require('store/plugins/expire')
150
151
// Custom store with specific backends and plugins
152
var customStore = engine.createStore(
153
[localStorage, memoryStorage], // Try localStorage, fallback to memory
154
[expirePlugin], // Include expiration support
155
'myapp' // Namespace all keys with 'myapp'
156
)
157
158
customStore.set('config', { theme: 'dark' }, Date.now() + 86400000) // 24 hours
159
```
160
161
### Storage Backends
162
163
Individual storage mechanisms that provide the underlying persistence.
164
165
#### localStorage Backend
166
167
Browser localStorage API backend.
168
169
```javascript { .api }
170
var localStorage = require('store/storages/localStorage')
171
172
// Storage backend interface
173
interface Storage {
174
name: string // 'localStorage'
175
read(key: string): string | null
176
write(key: string, data: string): void
177
each(callback: (value: string, key: string) => void): void
178
remove(key: string): void
179
clearAll(): void
180
}
181
```
182
183
#### sessionStorage Backend
184
185
Browser sessionStorage API backend (data cleared when tab closes).
186
187
```javascript { .api }
188
var sessionStorage = require('store/storages/sessionStorage')
189
```
190
191
#### cookieStorage Backend
192
193
Document.cookie-based storage backend.
194
195
```javascript { .api }
196
var cookieStorage = require('store/storages/cookieStorage')
197
```
198
199
#### memoryStorage Backend
200
201
In-memory storage backend (data lost on page reload).
202
203
```javascript { .api }
204
var memoryStorage = require('store/storages/memoryStorage')
205
```
206
207
#### Legacy Storage Backends
208
209
For older browsers:
210
211
```javascript { .api }
212
var oldFFGlobalStorage = require('store/storages/oldFF-globalStorage')
213
var oldIEUserDataStorage = require('store/storages/oldIE-userDataStorage')
214
```
215
216
#### All Storage Backends
217
218
Convenience import for all storage backends in optimal fallback order based on browser support and persistence capabilities.
219
220
```javascript { .api }
221
var allStorages = require('store/storages/all')
222
// Array containing all storage backends in priority order:
223
// [localStorage, oldFF-globalStorage, oldIE-userDataStorage,
224
// cookieStorage, sessionStorage, memoryStorage]
225
```
226
227
**Storage Priority Order:**
228
1. **localStorage** - Modern browsers, persistent across sessions (~2MB capacity)
229
2. **oldFF-globalStorage** - Firefox 6-7 compatibility, persistent
230
3. **oldIE-userDataStorage** - IE6-7 compatibility, persistent (~64KB capacity)
231
4. **cookieStorage** - Cookie fallback for Safari private mode (~4KB capacity)
232
5. **sessionStorage** - Session-only storage, cleared when tab closes
233
6. **memoryStorage** - In-memory fallback, no persistence (cleared on page reload)
234
235
**Usage Examples:**
236
237
```javascript
238
var engine = require('store/src/store-engine')
239
var allStorages = require('store/storages/all')
240
241
// Store will automatically choose the first working storage
242
var store = engine.createStore(allStorages, [])
243
244
// Manual storage selection
245
var localStorage = require('store/storages/localStorage')
246
var memoryStorage = require('store/storages/memoryStorage')
247
248
var store = engine.createStore([localStorage, memoryStorage], [])
249
// Will use localStorage if available, fallback to memoryStorage
250
```
251
252
### Namespace Support
253
254
Create isolated storage contexts to avoid key collisions.
255
256
```javascript { .api }
257
/**
258
* Create namespaced store instance
259
* @param {string} namespace - Namespace identifier (alphanumeric + underscore/dash)
260
* @returns {Object} Namespaced store instance
261
*/
262
store.namespace(namespace)
263
264
/**
265
* Check if store has specific namespace
266
* @param {string} namespace - Namespace to check
267
* @returns {boolean} True if store has the namespace
268
*/
269
store.hasNamespace(namespace)
270
```
271
272
**Usage Examples:**
273
274
```javascript
275
// Create separate namespaces for different app sections
276
var userStore = store.namespace('user')
277
var appStore = store.namespace('app')
278
var cacheStore = store.namespace('cache')
279
280
// Data is isolated by namespace
281
userStore.set('preferences', { theme: 'dark' })
282
appStore.set('preferences', { language: 'en' })
283
cacheStore.set('data', { timestamp: Date.now() })
284
285
console.log(userStore.get('preferences')) // { theme: 'dark' }
286
console.log(appStore.get('preferences')) // { language: 'en' }
287
console.log(userStore.get('data')) // undefined
288
289
// Check namespace
290
console.log(userStore.hasNamespace('user')) // true
291
console.log(userStore.hasNamespace('app')) // false
292
293
// Create stores with namespace from start
294
var engine = require('store/src/store-engine')
295
var storages = require('store/storages/all')
296
297
var adminStore = engine.createStore(storages, [], 'admin')
298
var guestStore = engine.createStore(storages, [], 'guest')
299
300
adminStore.set('permissions', ['read', 'write', 'delete'])
301
guestStore.set('permissions', ['read'])
302
```
303
304
### Advanced Configuration
305
306
#### Script Tag Usage
307
308
For script tag usage without bundlers:
309
310
```html { .api }
311
<!-- Legacy build (maximum compatibility) -->
312
<script src="path/to/store.legacy.min.js"></script>
313
314
<!-- Modern build (smaller size) -->
315
<script src="path/to/store.modern.min.js"></script>
316
317
<!-- Everything build (all features) -->
318
<script src="path/to/store.everything.min.js"></script>
319
```
320
321
**Usage Examples:**
322
323
```html
324
<script src="https://cdn.jsdelivr.net/npm/store@2.0.12/dist/store.legacy.min.js"></script>
325
<script>
326
// Store is available globally
327
store.set('user', { name: 'Alice' })
328
console.log(store.get('user').name) // 'Alice'
329
</script>
330
```
331
332
#### Node.js Environment
333
334
Store.js works in Node.js with a localStorage polyfill:
335
336
```javascript { .api }
337
// Install localStorage polyfill for Node.js
338
// npm install localStorage
339
340
// Store.js will automatically detect and use it
341
var store = require('store')
342
store.set('data', 'works in Node.js')
343
```
344
345
#### Storage Testing
346
347
Test if specific storage backends work in the current environment:
348
349
```javascript { .api }
350
var engine = require('store/src/store-engine')
351
var localStorage = require('store/storages/localStorage')
352
353
// Test storage manually
354
var testStore = engine.createStore([localStorage], [])
355
if (testStore.enabled) {
356
console.log('localStorage is working')
357
} else {
358
console.log('localStorage is not available')
359
}
360
```
361
362
#### Plugin Development
363
364
Create custom plugins to extend functionality:
365
366
```javascript { .api }
367
/**
368
* Plugin function that returns method implementations
369
* @returns {Object} Object with method names as keys and functions as values
370
*/
371
function myPlugin() {
372
return {
373
// Method implementations that can override or extend store methods
374
customMethod: function() {
375
// Plugin implementation
376
}
377
}
378
}
379
380
store.addPlugin(myPlugin)
381
```
382
383
**Usage Examples:**
384
385
```javascript
386
// Custom plugin example
387
function timestampPlugin() {
388
return {
389
setWithTimestamp: function(_, key, value) {
390
var data = {
391
value: value,
392
timestamp: Date.now()
393
}
394
this.set(key, data)
395
},
396
397
getWithAge: function(_, key) {
398
var data = this.get(key)
399
if (data && data.timestamp) {
400
return {
401
value: data.value,
402
age: Date.now() - data.timestamp
403
}
404
}
405
return data
406
}
407
}
408
}
409
410
store.addPlugin(timestampPlugin)
411
412
// Use custom plugin methods
413
store.setWithTimestamp('data', 'hello world')
414
setTimeout(function() {
415
var result = store.getWithAge('data')
416
console.log(result.value) // 'hello world'
417
console.log(result.age) // ~1000 (milliseconds)
418
}, 1000)
419
```