unstorage
repository·main·Indexed 25 days ago
https://github.com/unjs/unstorageA universal asynchronous Key-Value storage API designed for Browsers, NodeJS, and Workers. It features a tiny core, multi-driver mounting, automatic JSON serialization, and support for custom drivers via defineDriver. The library provides a consistent interface for operations like getItem, setItem, and removeItem, and includes utilities for namespacing with prefixStorage, taking snapshots, and exposing storage via an HTTP server.
What's inside unstorage
- Unstorage provides a wide variety of built-in drivers to store data across different environments and services. You can choose a driver based on your runtime (Node.js, Browser, Mobile) or your preferred storage backend (SQL, NoSQL, Cloud, Memory, etc.).
Use the Capacitor Preferences driver
mainThe
capacitor-preferencesdriver allows you to store data via the Capacitor Preferences API on mobile devices or via local storage on the web. This is useful for persistent key-value storage in Capacitor-based mobile applications.import { createStorage } from "unstorage"; import capacitorPreferences from "unstorage/drivers/capacitor-preferences"; const storage = createStorage({ driver: capacitorPreferences({ base: "test", }), });Use the Node.js Filesystem (Lite) driver
mainThe
fs-litedriver uses the pure Node.js API without extra dependencies (such aschokidar). Use this if you want to minimize your dependency footprint.import { createStorage } from "unstorage"; import fsLiteDriver from "unstorage/drivers/fs-lite"; const storage = createStorage({ driver: fsLiteDriver({ base: "./tmp" }), });Install the Upstash driver for Unstorage
mainTo use the Upstash Redis driver with Unstorage, you must install the@upstash/redispackage in your project, as Unstorage uses it internally to connect to your database.Use the Vercel Blob driver
mainThe
vercel-blobdriver allows you to store data in a Vercel Blob Store. You must install the@vercel/blobdependency to use this driver.Configuration Options:
access: Access mode. Must be either"public"or"private".base: Prefix to prepend to all keys for namespacing.token: Rest API token for the Vercel Blob store. If omitted, it defaults to theBLOB_READ_WRITE_TOKENenvironment variable.envPrefix: Prefix for the token environment variable. Defaults to"BLOB"(resulting inBLOB_READ_WRITE_TOKEN).
Use Azure Blob Storage driver
mainStore data in Azure Blob Storage. Each entry is stored in a separate blob using the key as the blob name and the value as the content. All entries share the same container.
Installation:
npm install @azure/storage-blob @azure/identityNote: Ensure the target container exists in your storage account before use.
Authentication:
DefaultAzureCredential(Recommended): RequiresStorage Blob Data Contributorrole.AzureNamedKeyCredential(Node.js only): UsesaccountNameandaccountKey.AzureSASCredential: UsesaccountNameandsasToken.connectionString(Node.js only): Uses the storage account connection string (not recommended for security).
import { createStorage } from "unstorage"; import azureStorageBlobDriver from "unstorage/drivers/azure-storage-blob"; const storage = createStorage({ driver: azureStorageBlobDriver({ accountName: "myazurestorageaccount", }), });Use the Filesystem (Node.js) driver
mainThe
fsdriver allows you to store data in the filesystem using the Node.js API. It maps data to the real filesystem using a directory structure for nested keys. It supports file watching viachokidarand implements metadata for each key, includingmtime(last modified time),atime(last access time), andsize(file size) usingfs.stat.Driver name:
fsorfs-lite(when using the lite version)import { createStorage } from "unstorage"; import fsDriver from "unstorage/drivers/fs"; const storage = createStorage({ driver: fsDriver({ base: "./tmp" }), });Use the LRU Cache driver
mainThe
lru-cachedriver keeps cached data in memory using thelru-cachepackage. It is useful for high-performance, in-memory storage with a limit on the number of items or total size.Key Details:
- Driver name:
lru-cache - Default capacity: The
maxsetting is set to1000items by default. - Size calculation: By default, the
sizeCalculationoption is implemented based on the buffer size of both the key and the value. - Configuration: You can pass any supported options from the
lru-cachepackage to the driver function.
import { createStorage } from "unstorage"; import lruCacheDriver from "unstorage/drivers/lru-cache"; const storage = createStorage({ driver: lruCacheDriver(), });- Driver name:
Use the Deno KV driver in Node.js
mainTo use Deno KV in a Node.js environment (Node 18+), use the
deno-kv-nodedriver. This driver uses the@deno/kvpackage to access remote Deno Deploy databases via the KV Connect protocol or to create local SQLite-backed databases.First, install the required peer dependency:
npm install @deno/kvThen, initialize the storage in your application:
import { createStorage } from "unstorage"; import denoKVNodedriver from "unstorage/drivers/deno-kv-node"; const storage = createStorage({ driver: denoKVNodedriver({ // path: ":memory:", // base: "", }), });Use Cloudflare R2 via Worker Bindings
mainUse the
cloudflare-r2-bindingdriver to access Cloudflare R2 buckets from a Cloudflare Worker environment.Warning: This is an experimental driver. It only works in a Cloudflare Worker environment and cannot be used in other runtimes like Node.js.
import { createStorage } from "unstorage"; import cloudflareR2BindingDriver from "unstorage/drivers/cloudflare-r2-binding"; // Using binding name to be picked from globalThis const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: "BUCKET" }), }); // Directly setting binding const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: globalThis.BUCKET }), }); // Using from Durable Objects and Workers using Modules Syntax const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: this.env.BUCKET }), });Configure the PlanetScale table schema
mainThe PlanetScale driver stores KV information in a table with specific columns. You must create a table in your PlanetScale database using the following SQL schema, replacing
<storage>with your desired table name:create table <storage> ( id varchar(255) not null primary key, value longtext, created_at timestamp default current_timestamp, updated_at timestamp default current_timestamp on update current_timestamp );Use the HTTP driver for remote storage
mainThe
httpdriver allows you to use a remote HTTP/HTTPS endpoint as a data storage backend. It implements metadata for each key, includingmtime(last modified time) andstatusfrom HTTP headers, by performingHEADrequests.To use it, import
httpDriverfromunstorage/drivers/httpand provide abaseURL.import { createStorage } from "unstorage"; import httpDriver from "unstorage/drivers/http"; const storage = createStorage({ driver: httpDriver({ base: "http://cdn.com" }), });