store.js

Cross-browser storage for all use cases, used across the web.

README

Store.js
========

Cross-browser storage for all use cases, used across the web.
Circle CI npm version npm

Store.js has been around since 2010 (first commit, v1 release). It is used in production on tens of thousands of websites, such as cnn.com, dailymotion.com, & many more.

Store.js provides basic key/value storage functionality (get/set/remove/each) as well as a rich set of plug-in storages and extra functionality.


- All you need to get started
- API
- All of them, pretty much :)
- Additional common functionality
- Choose which build is right for you
- Storages provide underlying persistence


Basic Usage

All you need to know to get started:

API


store.js exposes a simple API for cross-browser local storage:

  1. ``` js
  2. // Store current user
  3. store.set('user', { name:'Marcus' })

  4. // Get current user
  5. store.get('user')

  6. // Remove current user
  7. store.remove('user')

  8. // Clear all keys
  9. store.clearAll()

  10. // Loop over all stored values
  11. store.each(function(value, key) {
  12. console.log(key, '==', value)
  13. })
  14. ```

Installation


Using npm:

  1. ```sh
  2. npm i store
  3. ```

  1. ``` js
  2. // Example store.js usage with npm
  3. var store = require('store')
  4. store.set('user', { name:'Marcus' })
  5. store.get('user').name == 'Marcus'
  6. ```

Using script tag (first download one of the builds):

  1. ``` html
  2. <script src="path/to/my/store.legacy.min.js"></script>
  3. <script>
  4. store.set('user', { name:'Marcus' })
  5. store.get('user').name == 'Marcus'
  6. </script>
  7. ```



Supported Browsers

All of them, pretty much :)

To support all browsers (including IE 6, IE 7, Firefox 4, etc.), use require('store') (alias for require('store/dist/store.legacy')) or store.legacy.min.js.

To save some kilobytes but still support all modern browsers, use require('store/dist/store.modern') or store.modern.min.js instead.

List of supported browsers


- Tested on IE6+
- Tested on iOS 8+
- Tested on Android 4+
- Tested on Firefox 4+
- Tested on Chrome 27+
- Tested on Safari 5+
- Tested on Opera 11+
- Tested on Node (with https://github.com/coolaj86/node-localStorage)




Plugins

Plugins provide additional common functionality that some users might need:

List of all Plugins


- all.js:                      All the plugins in one handy place.
- defaults.js:            Declare default values. Example usage
- dump.js:                    Dump all stored values. Example usage
- events.js:                Get notified when stored values change. Example usage
- expire.js:                Expire stored values at a given time. Example usage
- observe.js:              Observe stored values and their changes. Example usage
- operations.js:        Useful operations like push, shift & assign. Example usage
- update.js:                Update a stored object, or create it if null. Example usage
- v1-backcompat.js:  Full backwards compatibility with store.js v1. Example usage

Using Plugins


With npm:

  1. ``` js
  2. // Example plugin usage:
  3. var expirePlugin = require('store/plugins/expire')
  4. store.addPlugin(expirePlugin)
  5. ```

If you're using script tags, you can either use store.everything.min.js (which
has all plugins built-in), or clone this repo to add or modify a build and run make build.

Write your own plugin


A store.js plugin is a function that returns an object that gets added to the store.
If any of the plugin functions overrides existing functions, the plugin function can still call
the original function using the first argument (super_fn).

  1. ``` js
  2. // Example plugin that stores a version history of every value
  3. var versionHistoryPlugin = function() {
  4. var historyStore = this.namespace('history')
  5. return {
  6.   set: function(super_fn, key, value) {
  7.    var history = historyStore.get(key) || []
  8.    history.push(value)
  9.    historyStore.set(key, history)
  10.    return super_fn()
  11.   },
  12.   getHistory: function(key) {
  13.    return historyStore.get(key)
  14.   }
  15. }
  16. }
  17. store.addPlugin(versionHistoryPlugin)
  18. store.set('foo', 'bar 1')
  19. store.set('foo', 'bar 2')
  20. store.getHistory('foo') == ['bar 1', 'bar 2']
  21. ```

Let me know if you need more info on writing plugins. For the moment I recommend
taking a look at the current plugins. Good example plugins are



Builds

Choose which build is right for you!

List of default builds


- store.everything.min.js: All the plugins, all the storages. Source
- store.legacy.min.js: Full support for all tested browsers. Add plugins separately. Source
- store.modern.min.js: Full support for all modern browsers. Add plugins separately. Source
- store.v1-backcompat.min.js: Full backwards compatibility with store.js v1. Source

Make your own Build


If you're using npm you can create your own build:

  1. ``` js
  2. // Example custom build usage:
  3. var engine = require('store/src/store-engine')
  4. var storages = [
  5. require('store/storages/localStorage'),
  6. require('store/storages/cookieStorage')
  7. ]
  8. var plugins = [
  9. require('store/plugins/defaults'),
  10. require('store/plugins/expire')
  11. ]
  12. var store = engine.createStore(storages, plugins)
  13. store.set('foo', 'bar', new Date().getTime() + 3000) // Using expire plugin to expire in 3 seconds
  14. ```




Storages
Store.js will pick the best available storage, and automatically falls back to the first available storage that works:

List of all Storages


- all.js                                     All the storages in one handy place.
- localStorage.js                   Store values in localStorage. Great for all modern browsers.
- sessionStorage.js               Store values in sessionStorage.
- cookieStorage.js                 Store values in cookies. Useful for Safari Private mode.
- memoryStorage.js                 Store values in memory. Great fallback to ensure store functionality at all times.
- oldFF-globalStorage.js     Store values in globalStorage. Only useful for legacy Firefox 3+.
- oldIE-userDataStorage.js Store values in userData. Only useful for legacy IE 6+.


Storages limits


Each storage has different limits, restrictions and overflow behavior on different browser. For example, Android has has a 4.57M localStorage limit in 4.0, a 2.49M limit in 4.1, and a 4.98M limit in 4.2... Yeah.

To simplify things we provide these recommendations to ensure cross browser behavior:

| Storage         | Targets                | Recommendations                 | More info                                        |
|:----------------|:-----------------------|:--------------------------------|:-------------------------------------------------|
| all             | All browsers           | Store < 1 million characters    | (Except Safari Private mode)                     |
| all             | All & Private mode     | Store < 32 thousand characters  | (Including Safari Private mode)                  |
| localStorage    | Modern browsers        | Max 2mb  (~1M chars)            | [limits][local-limits], [android][local-android] |
| sessionStorage  | Modern browsers        | Max 5mb  (~2M chars)            | [limits][session-limits]                         |
| cookieStorage   | Safari Private mode    | Max 4kb  (~2K chars)            | [limits][cookie-limits]                          |
| userDataStorage | IE5, IE6 & IE7         | Max 64kb (~32K chars)           | [limits][userdata-limits]                        |
| globalStorage   | Firefox 2-5            | Max 5mb  (~2M chars)            | [limits][global-limits]                          |
| memoryStorage   | All browsers, fallback | Does not persist across pages!  |                                                  |

[local-limits]: https://arty.name/localstorage.html
[local-android]: http://dev-test.nemikor.com/web-storage/support-test/
[session-limits]: http://stackoverflow.com/questions/15840976/how-large-is-html5-session-storage
[cookie-limits]: http://browsercookielimits.squawky.net/
[userdata-limits]: https://msdn.microsoft.com/en-us/library/ms533015(v=vs.85).aspx
[global-limits]: https://github.com/jeremydurham/persist-js/blob/master/README.md#4-size-limits
[more]: https://www.html5rocks.com/en/tutorials/offline/quota-research/


Write your own Storage


Chances are you won't ever need another storage. But if you do...

See storages/ for examples. Two good examples are memoryStorage and localStorage.

Basically, you just need an object that looks like this:

  1. ``` js
  2. // Example custom storage
  3. var storage = {
  4. name: 'myStorage',
  5. read: function(key) { ... },
  6. write: function(key, value) { ... },
  7. each: function(fn) { ... },
  8. remove: function(key) { ... },
  9. clearAll: function() { ... }
  10. }
  11. var store = require('store').createStore(storage)
  12. ```