![Introducing Dashboard Analytics](https://cdn.sanity.io/images/cgdhsj6q/production/af327c5bd94708db501516a75da6870aef894c64-2286x1522.png?w=400&fit=max&auto=format)
Product
Introducing Dashboard Analytics
We're introducing a new Analytics feature in the Socket dashboard so you can view changes in your organization's and repositories' alerts over time.
idb-keyval
Advanced tools
The idb-keyval npm package is a simple key-value store backed by IndexedDB. It provides a straightforward API for storing, retrieving, and managing data in the browser's IndexedDB, making it easier to work with compared to the native IndexedDB API.
Set a value
This feature allows you to store a value in the IndexedDB with a specified key. The code sample demonstrates how to set a value 'value' with the key 'key'.
import { set } from 'idb-keyval';
set('key', 'value').then(() => console.log('Value set!'));
Get a value
This feature allows you to retrieve a value from the IndexedDB using a specified key. The code sample demonstrates how to get the value associated with the key 'key'.
import { get } from 'idb-keyval';
get('key').then(val => console.log('Value:', val));
Delete a value
This feature allows you to delete a value from the IndexedDB using a specified key. The code sample demonstrates how to delete the value associated with the key 'key'.
import { del } from 'idb-keyval';
del('key').then(() => console.log('Value deleted!'));
Clear all values
This feature allows you to clear all values from the IndexedDB. The code sample demonstrates how to clear all stored values.
import { clear } from 'idb-keyval';
clear().then(() => console.log('All values cleared!'));
Get all keys
This feature allows you to retrieve all keys from the IndexedDB. The code sample demonstrates how to get all keys stored in the database.
import { keys } from 'idb-keyval';
keys().then(keys => console.log('Keys:', keys));
LocalForage is a fast and simple storage library for JavaScript. It improves the offline experience of your web app by using asynchronous storage (IndexedDB or WebSQL) with a simple, localStorage-like API. Compared to idb-keyval, LocalForage offers more flexibility in terms of storage backends and a more extensive API.
Dexie is a minimalistic wrapper for IndexedDB that provides a more powerful and developer-friendly API. It supports advanced querying, transactions, and versioning. Compared to idb-keyval, Dexie is more feature-rich and suitable for complex use cases involving IndexedDB.
The idb library is a small, well-tested library that makes working with IndexedDB more pleasant. It provides a promise-based API and simplifies many common tasks. Compared to idb-keyval, idb offers a more comprehensive API for interacting with IndexedDB, while idb-keyval focuses on simplicity and ease of use.
This is a super-simple promise-based keyval store implemented with IndexedDB, originally based on async-storage by Mozilla.
It's small and tree-shakeable. If you only use get/set, the library is ~250 bytes (brotli'd), if you use all methods it's ~450 bytes.
localForage offers similar functionality, but supports older browsers with broken/absent IDB implementations. Because of that, it's orders of magnitude bigger (~7k).
This is only a keyval store. If you need to do more complex things like iteration & indexing, check out IDB on NPM (a little heavier at 1k). The first example in its README is how to create a keyval store.
npm install idb-keyval
Now you can require/import idb-keyval
:
import { get, set } from 'idb-keyval';
If you're targeting older versions of IE, you may have more luck with:
// Import a Promise polyfill
import 'es6-promise/auto';
import { get, set } from 'idb-keyval/dist/esm-compat';
dist/cjs/index.js
CommonJS module.dist/cjs-compat/index.js
CommonJS module, transpiled for older browsers.dist/esm/index.js
EcmaScript module.dist/esm-compat/index.js
EcmaScript module, transpiled for older browsers.dist/iife/index.js
Minified plain JS, which creates an idbKeyval
global containing all methods.dist/iife-compat/index.js
As above, but transpiled for older browsers.These built versions are also available on jsDelivr, e.g.:
<script src="https://cdn.jsdelivr.net/npm/idb-keyval@4/dist/iife/index.js"></script>
<!-- Or in modern browsers: -->
<script type="module">
import {
get,
set,
} from 'https://cdn.jsdelivr.net/npm/idb-keyval@4/dist/esm/index.js';
</script>
import { set } from 'idb-keyval';
set('hello', 'world');
Since this is IDB-backed, you can store anything structured-clonable (numbers, arrays, objects, dates, blobs etc), although old Edge doesn't support null
. Keys can be numbers, strings, Date
s, (IDB also allows arrays of those values, but IE doesn't support it).
All methods return promises:
import { set } from 'idb-keyval';
set('hello', 'world')
.then(() => console.log('It worked!'))
.catch((err) => console.log('It failed!', err));
import { get } from 'idb-keyval';
// logs: "world"
get('hello').then((val) => console.log(val));
If there is no 'hello' key, then val
will be undefined
.
Set many keyval pairs at once. This is faster than calling set
multiple times.
import { set, setMany } from 'idb-keyval';
// Instead of:
Promise.all([set(123, 456), set('hello', 'world')])
.then(() => console.log('It worked!'))
.catch((err) => console.log('It failed!', err));
// It's faster to do:
setMany([
[123, 456],
['hello', 'world'],
])
.then(() => console.log('It worked!'))
.catch((err) => console.log('It failed!', err));
This operation is also atomic – if one of the pairs can't be added, none will be added.
Get many keys at once. This is faster than calling get
multiple times. Resolves with an array of values.
import { get, getMany } from 'idb-keyval';
// Instead of:
Promise.all([get(123), get('hello')]).then(([firstVal, secondVal]) =>
console.log(firstVal, secondVal),
);
// It's faster to do:
getMany([123, 'hello']).then(([firstVal, secondVal]) =>
console.log(firstVal, secondVal),
);
Transforming a value (eg incrementing a number) using get
and set
is risky, as both get
and set
are async and non-atomic:
// Don't do this:
import { get, set } from 'idb-keyval';
get('counter').then((val) =>
set('counter', (val || 0) + 1);
);
get('counter').then((val) =>
set('counter', (val || 0) + 1);
);
With the above, both get
operations will complete first, each returning undefined
, then each set operation will be setting 1
. You could fix the above by queuing the second get
on the first set
, but that isn't always each across multiple pieces of code. Instead:
// Instead:
import { update } from 'idb-keyval';
update('counter', (val) => (val || 0) + 1);
update('counter', (val) => (val || 0) + 1);
This will queue the updates automatically, so the first update
set the counter
to 1
, and the second update
sets it to 2
.
Delete a particular key from the store.
import { del } from 'idb-keyval';
del('hello');
Clear all values in the store.
import { clear } from 'idb-keyval';
clear();
Get all entries in the store. Each entry is an array of [key, value]
.
import { entries } from 'idb-keyval';
// logs: [[123, 456], ['hello', 'world']]
entries().then((entries) => console.log(entries));
Get all keys in the store.
import { keys } from 'idb-keyval';
// logs: [123, 'hello']
keys().then((keys) => console.log(keys));
Get all values in the store.
import { values } from 'idb-keyval';
// logs: [456, 'world']
values().then((values) => console.log(values));
By default, the methods above use an IndexedDB database named keyval-store
and an object store named keyval
. If you want to use something different, see custom stores.
The changes between 3.x and 4.x related to custom stores.
Old way:
// This no longer works in 4.x
import { Store, set } from 'idb-keyval';
const customStore = new Store('custom-db-name', 'custom-store-name');
set('foo', 'bar', customStore);
New way:
import { createStore, set } from 'idb-keyval';
const customStore = createStore('custom-db-name', 'custom-store-name');
set('foo', 'bar', customStore);
For more details, see custom stores.
2.x exported an object with methods:
// This no longer works in 3.x
import idbKeyval from 'idb-keyval';
idbKeyval.set('foo', 'bar');
Whereas in 3.x you import the methods directly:
import { set } from 'idb-keyval';
set('foo', 'bar');
This is better for minification, and allows tree shaking.
FAQs
A super-simple-small keyval store built on top of IndexedDB
The npm package idb-keyval receives a total of 514,079 weekly downloads. As such, idb-keyval popularity was classified as popular.
We found that idb-keyval demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
We're introducing a new Analytics feature in the Socket dashboard so you can view changes in your organization's and repositories' alerts over time.
Security News
A new OpenSSF report uncovers critical gaps in secure software training, with 75% of new developers unfamiliar with secure practices, highlighting urgent educational needs.
Security News
The 2023 Python Developers Survey reveals key trends in packaging, web frameworks, and developer demographics, highlighting a shift toward innovative tools as the Python community diversifies and grows among less experienced developers.