Convert Figma logo to code with AI

marcuswestin logostore.js

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

14,015
1,329
14,015
98

Top Related Projects

💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

21,334

Simple and fast JSON database

11,394

A Minimalistic Wrapper for IndexedDB

A lightweight clientside JSON document store,

Quick Overview

Store.js is a lightweight JavaScript library that provides a simple and consistent API for cross-browser local storage. It abstracts away the differences between various storage mechanisms (localStorage, globalStorage, userData behavior) and offers a unified interface for storing and retrieving data in the browser.

Pros

  • Cross-browser compatibility, supporting a wide range of browsers including older versions of IE
  • Fallback mechanisms to ensure data persistence even when localStorage is not available
  • Simple and intuitive API for easy integration into web applications
  • Lightweight with no dependencies, making it suitable for small to medium-sized projects

Cons

  • Limited feature set compared to more comprehensive storage libraries
  • Lack of built-in encryption for sensitive data storage
  • No built-in support for complex data structures or querying
  • Infrequent updates and maintenance (last major update was several years ago)

Code Examples

  1. Basic usage for storing and retrieving data:
store.set('user', { name: 'John Doe', age: 30 });
const user = store.get('user');
console.log(user.name); // Output: John Doe
  1. Removing data and clearing all stored items:
store.remove('user');
store.clearAll();
  1. Using namespaced storage:
const userStore = store.namespace('user');
userStore.set('preferences', { theme: 'dark', fontSize: 16 });
const prefs = userStore.get('preferences');
console.log(prefs.theme); // Output: dark
  1. Checking for storage support:
if (store.enabled) {
  console.log('Local storage is supported');
} else {
  console.log('Local storage is not supported in this browser');
}

Getting Started

To use Store.js in your project, follow these steps:

  1. Install Store.js via npm:

    npm install store
    
  2. Import and use Store.js in your JavaScript file:

    import store from 'store';
    
    // Set a value
    store.set('key', 'value');
    
    // Get a value
    const value = store.get('key');
    
    // Remove a value
    store.remove('key');
    
    // Clear all values
    store.clearAll();
    
  3. For browser usage without a module bundler, include the script in your HTML:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/store.js/2.0.12/store.min.js"></script>
    

Now you can use the store object to interact with local storage across different browsers.

Competitor Comparisons

💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

Pros of localForage

  • Supports multiple storage backends (IndexedDB, WebSQL, localStorage)
  • Provides a more robust API with promises and callbacks
  • Better performance for large datasets due to IndexedDB support

Cons of localForage

  • Larger file size and more complex implementation
  • Slightly steeper learning curve for developers
  • May be overkill for simple storage needs

Code Comparison

store.js:

store.set('user', { name: 'Marcus' })
console.log(store.get('user').name)

localForage:

localForage.setItem('user', { name: 'Marcus' }).then(function() {
  return localForage.getItem('user');
}).then(function(value) {
  console.log(value.name);
});

Key Differences

  • localForage uses a promise-based API, while store.js uses a simpler synchronous API
  • localForage provides more advanced features like key iteration and clear methods
  • store.js focuses on simplicity and cross-browser compatibility
  • localForage offers better performance for large datasets due to IndexedDB support

Use Cases

  • store.js: Ideal for simple key-value storage needs and projects requiring broad browser support
  • localForage: Better suited for applications dealing with larger datasets or requiring more advanced storage capabilities

Community and Maintenance

  • store.js: Smaller community, less frequent updates
  • localForage: Larger community, more active development and maintenance
21,334

Simple and fast JSON database

Pros of lowdb

  • Supports more complex data structures and querying capabilities
  • Provides a file-based JSON database, allowing data persistence across sessions
  • Offers a chainable API similar to Lodash for easier data manipulation

Cons of lowdb

  • Larger file size and more dependencies compared to store.js
  • Potentially slower performance for simple storage operations
  • Requires more setup and configuration for basic use cases

Code Comparison

store.js:

store.set('user', { name: 'John' })
console.log(store.get('user').name)  // Output: John

lowdb:

const adapter = new JSONFile('db.json')
const db = new Low(adapter)
await db.read()
db.data ||= { users: [] }
db.data.users.push({ name: 'John' })
await db.write()
console.log(db.data.users[0].name)  // Output: John

Summary

store.js is a lightweight solution for client-side storage with a simple API, while lowdb offers a more feature-rich, file-based JSON database with advanced querying capabilities. store.js is better suited for basic web storage needs, whereas lowdb is more appropriate for applications requiring persistent storage and complex data operations. The choice between the two depends on the specific requirements of your project, considering factors such as simplicity, performance, and data complexity.

11,394

A Minimalistic Wrapper for IndexedDB

Pros of Dexie.js

  • Provides a more robust and feature-rich API for working with IndexedDB
  • Supports complex querying and indexing capabilities
  • Offers better performance for large datasets and complex operations

Cons of Dexie.js

  • Has a steeper learning curve due to its more comprehensive API
  • Larger file size and potentially higher overhead for simple storage needs
  • May be overkill for basic key-value storage requirements

Code Comparison

Dexie.js:

const db = new Dexie('MyDatabase');
db.version(1).stores({
  friends: '++id, name, age'
});
await db.friends.add({name: 'John', age: 30});
const youngFriends = await db.friends.where('age').below(40).toArray();

store.js:

store.set('user', {name: 'John', age: 30});
const user = store.get('user');
store.remove('user');

Summary

Dexie.js is a more powerful solution for complex data storage needs, offering advanced querying and indexing capabilities. It's particularly well-suited for applications dealing with large datasets or requiring sophisticated data manipulation. However, it comes with a steeper learning curve and may be excessive for simple storage requirements.

store.js, on the other hand, provides a straightforward API for basic key-value storage, making it easier to use for simple data persistence needs. It's lightweight and requires minimal setup, but lacks the advanced features and performance optimizations of Dexie.js for complex data operations.

A lightweight clientside JSON document store,

Pros of Lawnchair

  • Supports multiple storage adapters (IndexedDB, WebSQL, DOM Storage)
  • Provides a more robust API with querying and batch operations
  • Offers plugins for additional functionality (e.g., pagination, migrations)

Cons of Lawnchair

  • Less actively maintained (last update in 2017)
  • More complex setup and usage compared to Store.js
  • Larger file size due to additional features

Code Comparison

Store.js:

store.set('user', { name: 'Marcus' })
console.log(store.get('user').name)

Lawnchair:

new Lawnchair({name: 'db'}, function(store) {
  store.save({key: 'user', name: 'Brian'})
  store.get('user', function(obj) {
    console.log(obj.name)
  })
})

Summary

Lawnchair offers more advanced features and flexibility with multiple storage adapters, making it suitable for complex data storage needs. However, it comes at the cost of a steeper learning curve and larger file size. Store.js, on the other hand, provides a simpler API and is more actively maintained, making it a better choice for basic storage requirements and projects that prioritize simplicity and ongoing support.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

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.

  1. Basic Usage
  2. Supported Browsers
  3. Plugins
  4. Builds
  5. Storages

Basic Usage

All you need to know to get started:

API

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

// Store current user
store.set('user', { name:'Marcus' })

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

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

// Clear all keys
store.clearAll()

// Loop over all stored values
store.each(function(value, key) {
	console.log(key, '==', value)
})

Installation

Using npm:

npm i store
// Example store.js usage with npm
var store = require('store')
store.set('user', { name:'Marcus' })
store.get('user').name == 'Marcus'

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

<!-- Example store.js usage with script tag -->
<script src="path/to/my/store.legacy.min.js"></script>
<script>
store.set('user', { name:'Marcus' })
store.get('user').name == 'Marcus'
</script>

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

Plugins

Plugins provide additional common functionality that some users might need:

List of all Plugins

Using Plugins

With npm:

// Example plugin usage:
var expirePlugin = require('store/plugins/expire')
store.addPlugin(expirePlugin)

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).

// Example plugin that stores a version history of every value
var versionHistoryPlugin = function() {
	var historyStore = this.namespace('history')
	return {
		set: function(super_fn, key, value) {
			var history = historyStore.get(key) || []
			history.push(value)
			historyStore.set(key, history)
			return super_fn()
		},
		getHistory: function(key) {
			return historyStore.get(key)
		}
	}
}
store.addPlugin(versionHistoryPlugin)
store.set('foo', 'bar 1')
store.set('foo', 'bar 2')
store.getHistory('foo') == ['bar 1', 'bar 2']

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 plugins/defaults, plugins/expire and plugins/events.

Builds

Choose which build is right for you!

List of default builds

Make your own Build

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

// Example custom build usage:
var engine = require('store/src/store-engine')
var storages = [
	require('store/storages/localStorage'),
	require('store/storages/cookieStorage')
]
var plugins = [
	require('store/plugins/defaults'),
	require('store/plugins/expire')
]
var store = engine.createStore(storages, plugins)
store.set('foo', 'bar', new Date().getTime() + 3000) // Using expire plugin to expire in 3 seconds

Storages

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

List of all Storages

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:

StorageTargetsRecommendationsMore info
allAll browsersStore < 1 million characters(Except Safari Private mode)
allAll & Private modeStore < 32 thousand characters(Including Safari Private mode)
localStorageModern browsersMax 2mb (~1M chars)limits, android
sessionStorageModern browsersMax 5mb (~2M chars)limits
cookieStorageSafari Private modeMax 4kb (~2K chars)limits
userDataStorageIE5, IE6 & IE7Max 64kb (~32K chars)limits
globalStorageFirefox 2-5Max 5mb (~2M chars)limits
memoryStorageAll browsers, fallbackDoes not persist across pages!

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:

// Example custom storage
var storage = {
	name: 'myStorage',
	read: function(key) { ... },
	write: function(key, value) { ... },
	each: function(fn) { ... },
	remove: function(key) { ... },
	clearAll: function() { ... }
}
var store = require('store').createStore(storage)

NPM DownloadsLast 30 Days