unstorage

repository·main·Indexed 25 days ago

https://github.com/unjs/unstorage

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

Tokens
21.7K
Snippets
70
Records
144
Agent score
82%

What's inside unstorage

  1. Explore Unstorage built-in drivers

    main
    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.).
  2. Use the Capacitor Preferences driver

    main

    The capacitor-preferences driver 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",
      }),
    });
  3. Use the Node.js Filesystem (Lite) driver

    main

    The fs-lite driver uses the pure Node.js API without extra dependencies (such as chokidar). 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" }),
    });
  4. Use the Vercel Blob driver

    main

    The vercel-blob driver allows you to store data in a Vercel Blob Store. You must install the @vercel/blob dependency 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 the BLOB_READ_WRITE_TOKEN environment variable.
    • envPrefix: Prefix for the token environment variable. Defaults to "BLOB" (resulting in BLOB_READ_WRITE_TOKEN).
  5. Use Azure Blob Storage driver

    main

    Store 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/identity

    Note: Ensure the target container exists in your storage account before use.

    Authentication:

    • DefaultAzureCredential (Recommended): Requires Storage Blob Data Contributor role.
    • AzureNamedKeyCredential (Node.js only): Uses accountName and accountKey.
    • AzureSASCredential: Uses accountName and sasToken.
    • 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",
      }),
    });
  6. Use the Filesystem (Node.js) driver

    main

    The fs driver 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 via chokidar and implements metadata for each key, including mtime (last modified time), atime (last access time), and size (file size) using fs.stat.

    Driver name: fs or fs-lite (when using the lite version)

    import { createStorage } from "unstorage";
    import fsDriver from "unstorage/drivers/fs";
    
    const storage = createStorage({
      driver: fsDriver({ base: "./tmp" }),
    });
  7. Use the LRU Cache driver

    main

    The lru-cache driver keeps cached data in memory using the lru-cache package. 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 max setting is set to 1000 items by default.
    • Size calculation: By default, the sizeCalculation option is implemented based on the buffer size of both the key and the value.
    • Configuration: You can pass any supported options from the lru-cache package to the driver function.
    import { createStorage } from "unstorage";
    import lruCacheDriver from "unstorage/drivers/lru-cache";
    
    const storage = createStorage({
      driver: lruCacheDriver(),
    });
  8. Use the Deno KV driver in Node.js

    main

    To use Deno KV in a Node.js environment (Node 18+), use the deno-kv-node driver. This driver uses the @deno/kv package 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/kv

    Then, 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: "",
      }),
    });
  9. Use Cloudflare R2 via Worker Bindings

    main

    Use the cloudflare-r2-binding driver 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 }),
    });
  10. Configure the PlanetScale table schema

    main

    The 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
    );
  11. Use the HTTP driver for remote storage

    main

    The http driver allows you to use a remote HTTP/HTTPS endpoint as a data storage backend. It implements metadata for each key, including mtime (last modified time) and status from HTTP headers, by performing HEAD requests.

    To use it, import httpDriver from unstorage/drivers/http and provide a base URL.

    import { createStorage } from "unstorage";
    import httpDriver from "unstorage/drivers/http";
    
    const storage = createStorage({
      driver: httpDriver({ base: "http://cdn.com" }),
    });