### Setup S3 Driver with Unstorage Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/s3.md Initialize the Unstorage with the S3 driver. Ensure you have installed the 'aws4fetch' peer dependency. Provide your S3 credentials and endpoint details. ```typescript import { createStorage } from "unstorage"; import s3Driver from "unstorage/drivers/s3"; const storage = createStorage({ driver: s3Driver({ accessKeyId: "", // Access Key ID secretAccessKey: "", // Secret Access Key endpoint: "", bucket: "", region: "", }), }); ``` -------------------------------- ### Install PlanetScale Database Package Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/planetscale.md Install the necessary PlanetScale database package for your project. ```json { "dependencies": { "@planetscale/database": "^1.5.0" } } ``` -------------------------------- ### Configure SQL Database Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/database.md Example of configuring the Unstorage SQL driver with db0 and a better-sqlite3 connector. Ensure db0 is installed and the connector is configured according to its documentation. ```js import { createDatabase } from "db0"; import { createStorage } from "unstorage"; import dbDriver from "unstorage/drivers/db0"; import sqlite from "db0/connectors/better-sqlite3"; // Learn more: https://db0.unjs.io const database = createDatabase( sqlite({ /* db0 connector options */ }), ); const storage = createStorage({ driver: dbDriver({ database, tableName: "custom_table_name", // Default is "unstorage" }), }); ``` -------------------------------- ### Initialize MongoDB Storage Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/mongodb.md Demonstrates how to create an Unstorage instance using the MongoDB driver. Ensure you have installed the 'mongodb' package. ```js import { createStorage } from "unstorage"; import mongodbDriver from "unstorage/drivers/mongodb"; const storage = createStorage({ driver: mongodbDriver({ connectionString: "CONNECTION_STRING", databaseName: "test", collectionName: "test", }), }); ``` -------------------------------- ### Initialize Unstorage with SessionStorage Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/browser.md This example demonstrates setting up Unstorage to use sessionStorage for data storage. Import the 'unstorage/drivers/localstorage' driver and specify 'sessionStorage' for the windowKey. ```js import { createStorage } from "unstorage"; import localStorageDriver from "unstorage/drivers/localstorage"; const storage = createStorage({ driver: localStorageDriver({ base: "app:", windowKey: "sessionStorage" }), }); ``` -------------------------------- ### Initialize Unstorage with LRU Cache Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/lru-cache.md Demonstrates how to import and use the LRU Cache driver with Unstorage. Ensure you have installed 'unstorage' and 'lru-cache'. ```js import { createStorage } from "unstorage"; import lruCacheDriver from "unstorage/drivers/lru-cache"; const storage = createStorage({ driver: lruCacheDriver(), }); ``` -------------------------------- ### Install @netlify/blobs Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/netlify.md Add the `@netlify/blobs` package as a devDependency to your project. This is required to use the Netlify Blobs driver. ```json { "devDependencies": { "@netlify/blobs": "latest" } } ``` -------------------------------- ### Create Storage with Capacitor Preferences Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/capacitor-preferences.md Demonstrates how to create a storage instance using the Capacitor Preferences driver. Ensure you have installed and synced `@capacitor/preferences` in your Capacitor project. ```javascript import { createStorage } from "unstorage"; import capacitorPreferences from "unstorage/drivers/capacitor-preferences"; const storage = createStorage({ driver: capacitorPreferences({ base: "test", }), }); ``` -------------------------------- ### Create Overlay Driver with Memory and FS Layers Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/overlay.md Demonstrates how to initialize the overlay driver with an in-memory layer and an fs layer. This setup directs writes to memory while reads can access both layers. ```javascript import { createStorage } from "unstorage"; import overlay from "unstorage/drivers/overlay"; import memory from "unstorage/drivers/memory"; import fs from "unstorage/drivers/fs"; const storage = createStorage({ driver: overlay({ layers: [memory(), fs({ base: "./data" })], }), }); ``` -------------------------------- ### Install Azure Key Vault Dependencies Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/azure.md Install the necessary Azure SDK packages for Key Vault secrets and identity management. ```bash npm install @azure/keyvault-secrets @azure/identity ``` -------------------------------- ### Install Unstorage Package Source: https://github.com/unjs/unstorage/blob/main/README.md Install the unstorage npm package using your preferred package manager. ```sh # yarn yarn add unstorage # npm npm install unstorage # pnpm pnpm add unstorage ``` -------------------------------- ### Create Unstorage with Azure Storage Table Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/azure.md Instantiate Unstorage using the Azure Storage Table driver. Ensure the `@azure/data-table` and `@azure/identity` packages are installed. This example uses the default partition key and table name. ```js import { createStorage } from "unstorage"; import azureStorageTableDriver from "unstorage/drivers/azure-storage-table"; const storage = createStorage({ driver: azureStorageTableDriver({ accountName: "myazurestorageaccount", }), }); ``` -------------------------------- ### Initialize Cloudflare KV HTTP Driver with Email and API Key Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/cloudflare.md This example shows how to set up the Cloudflare KV HTTP driver using email and API key authentication. This is an alternative to using an API token. ```javascript import { createStorage } from "unstorage"; import cloudflareKVHTTPDriver from "unstorage/drivers/cloudflare-kv-http"; // Using `email` and `apiKey` const storage = createStorage({ driver: cloudflareKVHTTPDriver({ accountId: "my-account-id", namespaceId: "my-kv-namespace-id", email: "me@example.com", apiKey: "my-api-key", }), }); ``` -------------------------------- ### Initialize Upstash Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/upstash.md Demonstrates how to create a Unstorage instance using the Upstash driver. Ensure you have installed `@upstash/redis` and configured your Upstash credentials via environment variables or direct options. ```js import { createStorage } from "unstorage"; import upstashDriver from "unstorage/drivers/upstash"; const storage = createStorage({ driver: upstashDriver({ base: "unstorage", // url: "", // or set UPSTASH_REDIS_REST_URL env // token: "", // or set UPSTASH_REDIS_REST_TOKEN env }), }); ``` -------------------------------- ### Install Redis Driver Dependency Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/redis.md Install the ioredis package, which is used internally by the Unstorage Redis driver. This is a prerequisite for using the Redis driver. ```bash npm install ioredis ``` -------------------------------- ### Initialize Unstorage with IndexedDB Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/browser.md Configure Unstorage to use IndexedDB for storing data in the browser. This requires installing the 'idb-keyval' package and importing the 'unstorage/drivers/indexedb' driver. ```js import { createStorage } from "unstorage"; import indexedDbDriver from "unstorage/drivers/indexedb"; const storage = createStorage({ driver: indexedDbDriver({ base: "app:" }), }); ``` -------------------------------- ### Initialize UploadThing Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/uploadthing.md Installs the uploadthing dependency and initializes the Unstorage driver with UploadThing. The API token can be provided directly or inferred from the UPLOADTHING_SECRET environment variable. ```javascript import { createStorage } from "unstorage"; import uploadthingDriver from "unstorage/drivers/uploadthing"; const storage = createStorage({ driver: uploadthingDriver({ // token: "", // UPLOADTHING_SECRET environment variable will be used if not provided. }), }); ``` -------------------------------- ### Create Netlify Blobs Storage Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/netlify.md Initialize Unstorage with the Netlify Blobs driver for a named store. This is the basic setup for using Netlify Blobs. ```javascript import { createStorage } from "unstorage"; import netlifyBlobsDriver from "unstorage/drivers/netlify-blobs"; const storage = createStorage({ driver: netlifyBlobsDriver({ name: "blob-store-name", }), }); ``` -------------------------------- ### Initialize Private Vercel Blob Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/vercel.md Set up the Unstorage driver for Vercel Blob with private access. Private blobs require authentication. Ensure a private blob store is created on the Vercel dashboard. Requires `@vercel/blob` installation. ```javascript import { createStorage } from "unstorage"; import vercelBlobDriver from "unstorage/drivers/vercel-blob"; const storage = createStorage({ driver: vercelBlobDriver({ access: "private", // token: "", // or set BLOB_READ_WRITE_TOKEN // base: "unstorage", // envPrefix: "BLOB", }), }); ``` -------------------------------- ### Unstorage Redis Single Instance Usage Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/redis.md Example of creating an Unstorage instance connected to a single Redis server. Ensure correct host, port, and authentication details are provided. ```javascript import { createStorage } from "unstorage"; import redisDriver from "unstorage/drivers/redis"; const storage = createStorage({ driver: redisDriver({ base: "unstorage", host: 'HOSTNAME', tls: true as any, port: 6380, password: 'REDIS_PASSWORD' }), }); ``` -------------------------------- ### getItem / get Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Gets the value of a key in storage. Resolves to either a JavaScript primitive value or `null`. ```APIDOC ## getItem(key, opts?) ### Description Gets the value of a key in storage. ### Method `getItem` or `get` ### Parameters #### Path Parameters - **key** (string) - Required - The key to retrieve. - **opts** (object) - Optional - Additional options. ### Request Example ```js await storage.getItem("foo:bar"); await storage.get("foo:bar"); ``` ### Response #### Success Response - **value** (any) - The retrieved value, or `null` if the key does not exist. ``` -------------------------------- ### getItems Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md (Experimental) Gets the value of multiple keys in storage in parallel. ```APIDOC ## getItems(items, opts) ### Description (Experimental) Gets the value of multiple keys in storage in parallel. ### Method `getItems` ### Parameters #### Path Parameters - **items** (Array<{ key: string, options?: object }>) - Required - An array of keys or objects with key and options to retrieve. - **opts** (object) - Optional - Additional options. ### Response #### Success Response - **value** (Array<{ key: string, value: any }>) - An array of objects containing the key and its retrieved value. ``` -------------------------------- ### getKeys / keys Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Get all keys. Returns an array of strings. Meta keys (ending with `$`) will be filtered. ```APIDOC ## getKeys(base?, opts?) ### Description Get all keys. Returns an array of strings. Meta keys (ending with `$`) will be filtered. If a base is provided, only keys starting with the base will be returned. ### Method `getKeys` or `keys` ### Parameters #### Path Parameters - **base** (string) - Optional - The base path to filter keys by. - **opts** (object) - Optional - Additional options. ### Request Example ```js await storage.getKeys(); await storage.keys(); ``` ### Response #### Success Response - **keys** (Array) - An array of keys found in storage. ``` -------------------------------- ### Get All Keys Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Retrieve an array of all keys in the storage. Meta keys are filtered out. Optionally, filter keys by a base path. ```javascript await storage.getKeys(); ``` ```javascript await storage.keys(); ``` -------------------------------- ### Initialize Azure Blob Storage Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/azure.md Initialize the Unstorage with the Azure Blob Storage driver. Ensure you have installed `@azure/storage-blob` and `@azure/identity`. The `accountName` is a required option. ```js import { createStorage } from "unstorage"; import azureStorageBlobDriver from "unstorage/drivers/azure-storage-blob"; const storage = createStorage({ driver: azureStorageBlobDriver({ accountName: "myazurestorageaccount", }), }); ``` -------------------------------- ### getMeta Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Get metadata object for a specific key. ```APIDOC ## getMeta(key, opts = { nativeOnly? }) ### Description Get metadata object for a specific key. This data is fetched from driver native meta and custom meta set by `storage.setMeta`. ### Method `getMeta` ### Parameters #### Path Parameters - **key** (string) - Required - The key to get metadata for. - **opts** (object) - Optional - Options, e.g., `{ nativeOnly: true }` to only fetch driver native meta. ### Request Example ```js await storage.getMeta("foo:bar"); // For fs driver returns an object like { mtime, atime, size } ``` ### Response #### Success Response - **meta** (object) - The metadata object for the key. ``` -------------------------------- ### Get Item Value Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Retrieve the value associated with a key using `getItem` or its alias `get`. Returns the primitive value or null if the key does not exist. ```javascript await storage.getItem("foo:bar"); ``` ```javascript await storage.get("foo:bar"); ``` -------------------------------- ### Initialize Public Vercel Blob Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/vercel.md Configure the Unstorage driver to use Vercel Blob for storing public data. Public blobs are accessible via URL without authentication. Requires `@vercel/blob` installation. ```javascript import { createStorage } from "unstorage"; import vercelBlobDriver from "unstorage/drivers/vercel-blob"; const storage = createStorage({ driver: vercelBlobDriver({ access: "public", // token: "", // or set BLOB_READ_WRITE_TOKEN // base: "unstorage", // envPrefix: "BLOB", }), }); ``` -------------------------------- ### Define a Custom Unstorage Driver Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/4.custom-driver.md Implement the `defineDriver` function to create a new storage driver. This example shows the basic structure and required methods for a custom driver. ```javascript import { createStorage, defineDriver } from "unstorage"; const myStorageDriver = defineDriver((options) => { return { name: "my-custom-driver", options, async hasItem(key, _opts) {}, async getItem(key, _opts) {}, async setItem(key, value, _opts) {}, async removeItem(key, _opts) {}, async getKeys(base, _opts) {}, async clear(base, _opts) {}, async dispose() {}, async watch(callback) {}, }; }); const storage = createStorage({ driver: myStorageDriver(), }); ``` -------------------------------- ### getItemRaw Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Gets the value of a key in storage in raw format. Note: This is an experimental feature. ```APIDOC ## getItemRaw(key, opts?) ### Description Gets the value of a key in storage in raw format. This is an experimental feature. ### Method `getItemRaw` ### Parameters #### Path Parameters - **key** (string) - Required - The key to retrieve. - **opts** (object) - Optional - Additional options. ### Request Example ```js const value = await storage.getItemRaw("foo:bar.bin"); ``` ### Response #### Success Response - **value** (Buffer | Array | object) - The retrieved value in its raw format. ``` -------------------------------- ### Initialize Azure App Configuration Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/azure.md Initialize the Azure App Configuration driver for Unstorage. Requires installation of @azure/app-configuration and @azure/identity. Supports configuration via name, label, and prefix for key organization. ```javascript import { createStorage } from "unstorage"; import azureAppConfiguration from "unstorage/drivers/azure-app-configuration"; const storage = createStorage({ driver: azureAppConfiguration({ appConfigName: "unstoragetest", label: "dev", prefix: "app01", }), }); ``` -------------------------------- ### Get Metadata for a Key Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Retrieve metadata for a specific key. This includes driver-native metadata and custom metadata set via `setMeta`. ```javascript await storage.getMeta("foo:bar"); // For fs driver returns an object like { mtime, atime, size } ``` -------------------------------- ### Initialize Azure Cosmos DB Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/azure.md Initialize the Azure Cosmos DB driver for Unstorage. Requires installation of @azure/cosmos and @azure/identity. Configure with endpoint and account key, or rely on DefaultAzureCredential for authentication. ```javascript import { createStorage } from "unstorage"; import azureCosmos from "unstorage/drivers/azure-cosmos"; const storage = createStorage({ driver: azureCosmos({ endpoint: "ENDPOINT", accountKey: "ACCOUNT_KEY", }), }); ``` -------------------------------- ### Cloudflare KV Binding Driver Setup Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/cloudflare.md Configure Unstorage to use Cloudflare KV via bindings. Ensure your KV namespace is correctly bound in your Cloudflare Worker environment. ```javascript import { createStorage } from "unstorage"; import cloudflareKVBindingDriver from "unstorage/drivers/cloudflare-kv-binding"; // Directly setting binding const storage = createStorage({ driver: cloudflareKVBindingDriver({ binding: "STORAGE" }), }); ``` ```javascript // Using binding name to be picked from globalThis const storage = createStorage({ driver: cloudflareKVBindingDriver({ binding: globalThis.STORAGE }), }); ``` ```javascript // Using from Durable Objects and Workers using Modules Syntax const storage = createStorage({ driver: cloudflareKVBindingDriver({ binding: this.env.STORAGE }), }); ``` -------------------------------- ### Mounting a Filesystem Driver Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Mounts an additional storage driver, in this case, the filesystem driver, to a specific mount point. Writes to keys starting with the mount point will be directed to this driver. ```javascript import { createStorage } from "unstorage"; import fsDriver from "unstorage/drivers/fs"; // Create a storage container with default memory storage const storage = createStorage({}); storage.mount("/output", fsDriver({ base: "./output" })); // Writes to ./output/test file await storage.setItem("/output/test", "works"); // Adds value to in-memory storage await storage.setItem("/foo", "bar"); ``` -------------------------------- ### Create Unstorage with Deno KV Node.js Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/deno.md Initialize Unstorage using the deno-kv-node driver for Node.js environments. This requires installing the @deno/kv npm package. It allows access to Deno Deploy remote databases or local SQLite-backed KV databases. ```js import { createStorage } from "unstorage"; import denoKVNodedriver from "unstorage/drivers/deno-kv-node"; const storage = createStorage({ driver: denoKVNodedriver({ // path: ":memory:", // base: "", }), }); ``` -------------------------------- ### Get Item in Raw Format Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Retrieve the raw value of a key, which can be a Buffer, Array, or the driver's specific raw format. This is an experimental feature. ```javascript // Value can be a Buffer, Array or Driver's raw format const value = await storage.getItemRaw("foo:bar.bin"); ``` -------------------------------- ### Getting All Mount Points Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Retrieves a list of all registered mount points, optionally filtered by a base path and whether to include parent mount points. This helps in inspecting the storage hierarchy. ```javascript storage.mount("cache" /* ... */); storage.mount("cache:sub" /* ... */); storage.getMounts("cache:sub"); // => [{ base: "cache:sub", driver }] storage.getMounts("cache:"); // => [{ base: "cache:sub", driver }, { base: "cache:", driver }] storage.getMounts(""); storage.getMounts("cache:sub", { parents: true }); // => [{ base: "cache:sub", driver }, { base: "cache:", driver }, { base: "", driver }] ``` -------------------------------- ### Unstorage Redis Cluster Usage Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/redis.md Example of creating an Unstorage instance connected to a Redis cluster. Note the use of a hashtag prefix for the base to ensure keys hash to the same slot, which is crucial for cluster operations. ```javascript const storage = createStorage({ driver: redisDriver({ base: "{unstorage}", cluster: [ { port: 6380, host: "HOSTNAME", }, ], clusterOptions: { redisOptions: { tls: { servername: "HOSTNAME" }, password: "REDIS_PASSWORD", }, }, }), }); ``` -------------------------------- ### Use Unstorage in Netlify Edge Functions Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/netlify.md Import and use Unstorage with the Netlify Blobs driver within a Netlify edge function using URL imports. This is for custom edge function setups. ```javascript import { createStorage } from "https://esm.sh/unstorage"; import netlifyBlobsDriver from "https://esm.sh/unstorage/drivers/netlify-blobs"; export default async function handler(request: Request) { const storage = createStorage({ driver: netlifyBlobsDriver({ name: "blob-store-name", }), }); // ... } ``` -------------------------------- ### Getting Mount Point for a Key Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Retrieves the specific mount point, including its base path and driver, associated with a given key. This is useful for understanding where a key's data is stored. ```javascript storage.mount("cache" /* ... */); storage.mount("cache:routes" /* ... */); storage.getMount("cache:routes:foo:bar"); // => { base: "cache:routes:", driver: "..." } ``` -------------------------------- ### Watching for Storage Events Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Starts watching for changes across all mounted storage drivers. If a driver does not natively support watching, events will be emitted only when storage methods like `storage.*` are invoked. Returns a function to stop the watcher. ```javascript const unwatch = await storage.watch((event, key) => {}); // to stop this watcher await unwatch(); ``` -------------------------------- ### Create and Listen with Storage Server Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/3.http-server.md Programmatically create an HTTP server that exposes unstorage methods. Implement an `authorize` function to protect your server, especially in production. This server is an h3 instance and can be used with listhen. ```js import { listen } from "listhen"; import { createStorage } from "unstorage"; import { createStorageServer } from "unstorage/server"; const storage = createStorage(); const storageServer = createStorageServer(storage, { authorize(req) { // req: { key, type, event } if (req.type === "read" && req.key.startsWith("private:")) { throw new Error("Unauthorized Read"); } }, }); // Alternatively we can use `storageServer.handle` as a middleware await listen(storageServer.handle); ``` -------------------------------- ### Initialize Null Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/null.md Import and create a storage instance using the Null driver. This driver discards all data. ```javascript import { createStorage } from "unstorage"; import nullDriver from "unstorage/drivers/null"; const storage = createStorage({ driver: nullDriver(), }); ``` -------------------------------- ### Create GitHub Storage Instance Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/github.md Instantiate the unstorage with the GitHub driver, specifying the repository, branch, and a root directory. A GitHub token is recommended to avoid rate limits. ```javascript import { createStorage } from "unstorage"; import githubDriver from "unstorage/drivers/github"; const storage = createStorage({ driver: githubDriver({ repo: "nuxt/nuxt", branch: "main", dir: "/docs", }), }); ``` -------------------------------- ### Create Storage with Filesystem Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/fs.md Initializes unstorage with the 'fs' driver, mapping data to the real filesystem. The 'base' option specifies the root directory for storage operations. Supports watching via chokidar. ```javascript import { createStorage } from "unstorage"; import fsDriver from "unstorage/drivers/fs"; const storage = createStorage({ driver: fsDriver({ base: "./tmp" }), }); ``` -------------------------------- ### Create Unstorage with Deno KV Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/deno.md Initialize Unstorage using the deno-kv driver. Ensure Deno runtime is used with the --unstable-kv flag or Deno Deploy. The driver automatically maps Unstorage keys to Deno KV keys. ```js import { createStorage } from "unstorage"; import denoKVdriver from "unstorage/drivers/deno-kv"; const storage = createStorage({ driver: denoKVdriver({ // path: ":memory:", // base: "", // ttl: 60, // in seconds }), }); ``` -------------------------------- ### Basic Unstorage Usage Source: https://github.com/unjs/unstorage/blob/main/README.md Create a storage instance and retrieve an item using its key. Supports both colon and slash notation for keys. ```js import { createStorage } from "unstorage"; const storage = createStorage(/* opts */); await storage.getItem("foo:bar"); // or storage.getItem('/foo/bar') ``` -------------------------------- ### Initialize Cloudflare R2 Driver with Direct Binding Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/cloudflare.md Initialize Unstorage with the Cloudflare R2 driver by directly passing the R2 bucket binding from `globalThis`. ```javascript // Directly setting binding const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: globalThis.BUCKET }), }); ``` -------------------------------- ### Initialize Memory Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/memory.md Import and create a storage instance using the memory driver. This driver is suitable for development or temporary data storage. ```javascript import { createStorage } from "unstorage"; import memoryDriver from "unstorage/drivers/memory"; const storage = createStorage({ driver: memoryDriver(), }); ``` -------------------------------- ### Configure PlanetScale Unstorage Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/planetscale.md Initialize Unstorage with the PlanetScale driver, providing your database connection URL. ```javascript import { createStorage } from "unstorage"; import planetscaleDriver from "unstorage/drivers/planetscale"; const storage = createStorage({ driver: planetscaleDriver({ // This should certainly not be inlined in your code but loaded via runtime config // or environment variables depending on your framework/project. url: "mysql://xxxxxxxxx:************@xxxxxxxxxx.us-east-3.psdb.cloud/my-database?sslaccept=strict", // table: 'storage' }), }); ``` -------------------------------- ### Initialize Unstorage with LocalStorage Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/browser.md Use this snippet to create an Unstorage instance that persists data in the browser's localStorage. Ensure the 'unstorage/drivers/localstorage' module is imported. ```js import { createStorage } from "unstorage"; import localStorageDriver from "unstorage/drivers/localstorage"; const storage = createStorage({ driver: localStorageDriver({ base: "app:" }), }); ``` -------------------------------- ### Initialize HTTP Storage Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/http.md Initializes the Unstorage with the HTTP driver, specifying the base URL for remote storage. Ensure the base URL is correctly configured. ```js import { createStorage } from "unstorage"; import httpDriver from "unstorage/drivers/http"; const storage = createStorage({ driver: httpDriver({ base: "http://cdn.com" }), }); ``` -------------------------------- ### Connect to HTTP Server with Storage Client Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/3.http-server.md Use the http driver to connect to an unstorage HTTP server. This allows you to interact with the remote storage instance as if it were local. ```ts import { createStorage } from "unstorage"; import httpDriver from "unstorage/drivers/http"; const client = createStorage({ driver: httpDriver({ base: "SERVER_ENDPOINT", }), }); const keys = await client.getKeys(); ``` -------------------------------- ### Create Storage with Filesystem Lite Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/fs.md Initializes unstorage with the 'fs-lite' driver, which uses pure Node.js API without external dependencies. The 'base' option defines the isolation directory for storage. ```javascript import { createStorage } from "unstorage"; import fsLiteDriver from "unstorage/drivers/fs-lite"; const storage = createStorage({ driver: fsLiteDriver({ base: "./tmp" }), }); ``` -------------------------------- ### Initialize Cloudflare R2 Driver with Binding Name Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/cloudflare.md Initialize Unstorage with the Cloudflare R2 driver using the binding name. The binding name is expected to be available in `globalThis`. ```javascript 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" }), }); ``` -------------------------------- ### Create Deploy-Scoped Netlify Blobs Storage Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/netlify.md Initialize Unstorage with the Netlify Blobs driver using the `deployScoped` option. This ensures the store is only accessible by the current deploy. ```javascript import { createStorage } from "unstorage"; import netlifyBlobsDriver from "unstorage/drivers/netlify-blobs"; const storage = createStorage({ driver: netlifyBlobsDriver({ deployScoped: true, }), }); ``` -------------------------------- ### Initialize Cloudflare R2 Driver with Module Syntax Binding Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/cloudflare.md Initialize Unstorage with the Cloudflare R2 driver using bindings available through module syntax, typically in Durable Objects or Workers. ```javascript // Using from Durable Objects and Workers using Modules Syntax const storage = createStorage({ driver: cloudflareR2BindingDriver({ binding: this.env.BUCKET }), }); ``` -------------------------------- ### Initialize Vercel Runtime Cache Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/vercel.md Set up the Unstorage driver for Vercel Runtime Cache. This driver caches data within Vercel Functions. Optional parameters include base path, default TTL, and default tags. ```javascript import { createStorage } from "unstorage"; import vercelRuntimeCacheDriver from "unstorage/drivers/vercel-runtime-cache"; const storage = createStorage({ driver: vercelRuntimeCacheDriver({ // base: "app", // ttl: 60, // seconds // tags: ["v1"], }), }); ``` -------------------------------- ### Configure Nightly Unstorage (Project Dependency) Source: https://github.com/unjs/unstorage/blob/main/README.md Configure your project's devDependencies to use the nightly release channel of unstorage. ```json { "devDependencies": { "unstorage": "npm:unstorage-nightly" } } ``` -------------------------------- ### Configure Nightly Unstorage (Tool Resolution) Source: https://github.com/unjs/unstorage/blob/main/README.md Configure resolutions to use the nightly release channel of unstorage if it's a dependency of another tool in your project. ```json { "resolutions": { "unstorage": "npm:unstorage-nightly" } } ``` -------------------------------- ### Typed Storage Instance Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Shows how to create a storage instance with a predefined generic type for all its items. This ensures that all subsequent operations on this instance adhere to the specified type. ```typescript const storage = createStorage(); await storage.getItem("k"); // => storage.setItem("k", "val"); // Check ok storage.setItem("k", 123); // TS error ``` -------------------------------- ### Create PlanetScale Storage Table Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/planetscale.md Define the SQL schema for the table that will store your KV data in PlanetScale. ```sql create table ( 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 ); ``` -------------------------------- ### Migrate Netlify Blobs Stores Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/netlify.md Command to migrate objects in old global Netlify Blob stores to the new format using the Netlify CLI. This is necessary for compatibility with `@netlify/blobs` v7.0.0 and later. ```sh netlify recipes blobs-migrate ``` -------------------------------- ### Initialize Cloudflare KV HTTP Driver with API Token Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/cloudflare.md Use this snippet to initialize the Cloudflare KV HTTP driver using an API token for authentication. Ensure you have your account ID, namespace ID, and a valid API token. ```javascript import { createStorage } from "unstorage"; import cloudflareKVHTTPDriver from "unstorage/drivers/cloudflare-kv-http"; // Using `apiToken` const storage = createStorage({ driver: cloudflareKVHTTPDriver({ accountId: "my-account-id", namespaceId: "my-kv-namespace-id", apiToken: "supersecret-api-token", }), }); ``` -------------------------------- ### Take a Snapshot of Storage Data Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/2.utils.md The snapshot utility serializes all keys within an optional base path into a plain JavaScript object. The base path is removed from the keys in the snapshot. ```javascript import { snapshot } from "unstorage"; const data = await snapshot(storage, "/etc"); ``` -------------------------------- ### Initialize Unstorage with Azure Key Vault Driver Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/azure.md Create a Unstorage instance using the Azure Key Vault driver, specifying the vault name for your Azure Key Vault. ```javascript import { createStorage } from "unstorage"; import azureKeyVault from "unstorage/drivers/azure-key-vault"; const storage = createStorage({ driver: azureKeyVault({ vaultName: "testunstoragevault", }), }); ``` -------------------------------- ### Create Namespaced Storage Instance Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/2.utils.md Use prefixStorage to create a new storage instance with a virtual prefix. This is useful for organizing data and limiting access to specific key ranges. ```typescript import { createStorage, prefixStorage } from "unstorage"; const storage = createStorage(); const assetsStorage = prefixStorage(storage, "assets"); // Same as storage.setItem('assets:x', 'hello!') await assetsStorage.setItem("x", "hello!"); ``` -------------------------------- ### Set Item in Raw Format Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Add or update a key with its raw value. This is an experimental feature. `undefined` values result in item removal. ```javascript await storage.setItemRaw("data/test.bin", new Uint8Array([1, 2, 3])); ``` -------------------------------- ### Initialize Cloudflare KV HTTP Driver with User Service Key Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/cloudflare.md Initialize the Cloudflare KV HTTP driver with a user service key. This key is a restricted API key suitable for specific endpoints. ```javascript import { createStorage } from "unstorage"; import cloudflareKVHTTPDriver from "unstorage/drivers/cloudflare-kv-http"; // Using `userServiceKey` const storage = createStorage({ driver: cloudflareKVHTTPDriver({ accountId: "my-account-id", namespaceId: "my-kv-namespace-id", userServiceKey: "v1.0-my-service-key", }), }); ``` -------------------------------- ### Typing a Subset with prefixStorage Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Utilizes `prefixStorage` to create a typed sub-storage instance for a specific key prefix. This allows for granular type control over different sections of your storage. ```typescript const storage = createStorage(); const htmlStorage = prefixStorage(storage, "assets:html"); await htmlStorage.getItem("foo.html"); // => type Post = { title: string; content: string; }; const postStorage = prefixStorage(storage, "assets:posts"); await postStorage.getItem("foo.json"); // => ``` -------------------------------- ### dispose Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Disposes all mounted storages to ensure there are no open-handles left. Call it before exiting process. ```APIDOC ## dispose() ### Description Disposes all mounted storages to ensure there are no open-handles left. Call it before exiting process. Note: Dispose also clears in-memory data. ### Method `dispose` ### Request Example ```js await storage.dispose(); ``` ``` -------------------------------- ### setItems Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md (Experimental) Add/Update items in parallel to the storage. ```APIDOC ## setItems(items, opts) ### Description (Experimental) Add/Update items in parallel to the storage. ### Method `setItems` ### Parameters #### Path Parameters - **items** (Array<{ key: string, value: any, options?: object }>) - Required - An array of objects, each containing a key, value, and optional options. - **opts** (object) - Optional - Additional options. ### Response #### Success Response - **value** (Array<{ key: string, value: any }>) - An array of objects confirming the set items. ``` -------------------------------- ### clear Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Removes all stored key/values. If a base is provided, only mounts matching base will be cleared. ```APIDOC ## clear(base?, opts?) ### Description Removes all stored key/values. If a base is provided, only mounts matching base will be cleared. ### Method `clear` ### Parameters #### Path Parameters - **base** (string) - Optional - The base path to clear. - **opts** (object) - Optional - Additional options. ### Request Example ```js await storage.clear(); ``` ``` -------------------------------- ### setItem / set Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Add/Update a value to the storage. If the value is not a string, it will be stringified. ```APIDOC ## setItem(key, value, opts?) ### Description Add/Update a value to the storage. If the value is not a string, it will be stringified. If the value is `undefined`, it is the same as calling `removeItem(key)`. ### Method `setItem` or `set` ### Parameters #### Path Parameters - **key** (string) - Required - The key to set. - **value** (any) - Required - The value to store. Will be stringified if not a string. - **opts** (object) - Optional - Additional options. ### Request Example ```js await storage.setItem("foo:bar", "baz"); await storage.set("foo:bar", "baz"); ``` ``` -------------------------------- ### Typed getItem and getItemRaw Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates how to specify the expected return type for `getItem` and `getItemRaw` methods using generic type parameters. This aids in type safety when retrieving data. ```typescript await storage.getItem("k"); // => await storage.getItemRaw("k"); // => ``` -------------------------------- ### Set Item with Custom S3 Metadata Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/s3.md Store an item and include custom S3 metadata using the 'x-amz-meta-*' prefix for headers. Note that only custom metadata is returned by getMeta(). ```typescript // Set custom S3 metadata await storage.setItem("document.json", jsonString, { headers: { "Content-Type": "application/json", "x-amz-meta-author": "john-doe", }, }); ``` -------------------------------- ### Set Item with TTL and Tags in Vercel Runtime Cache Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/vercel.md Store data in the Vercel Runtime Cache with a specific Time-To-Live (TTL) and tags for expiration. This is useful for request-time caching within Vercel Functions. ```javascript await storage.setItem("user:123", JSON.stringify({ name: "Ana" }), { ttl: 3600, tags: ["user:123"], }); ``` -------------------------------- ### Check if Key Exists Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Use `hasItem` or its alias `has` to check if a specific key is present in the storage. ```javascript await storage.hasItem("foo:bar"); ``` ```javascript await storage.has("foo:bar"); ``` -------------------------------- ### setMeta Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Set custom meta for a specific key by adding a `$` suffix. ```APIDOC ## setMeta(key, opts?) ### Description Set custom meta for a specific key by adding a `$` suffix. This is equivalent to `storage.setItem(key + '$', metaObject)`. ### Method `setMeta` ### Parameters #### Path Parameters - **key** (string) - Required - The key to set meta for. - **opts** (object) - Required - The metadata object to set. ### Request Example ```js await storage.setMeta("foo:bar", { flag: 1 }); ``` ``` -------------------------------- ### Dispose Storage Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Clean up all mounted storages and release any open handles. This also clears in-memory data and should be called before exiting the process. ```javascript await storage.dispose(); ``` -------------------------------- ### Typed Storage Instance with Type Conflict Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Demonstrates a type conflict scenario where a generic type defined at the instance level is incompatible with a type specified for a specific method call. TypeScript will flag this as an error. ```typescript const storage = createStorage(); storage.setItem("k", 123); // TS error: is not compatible with ``` -------------------------------- ### Set Item Value Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Add or update a key-value pair in storage using `setItem` or its alias `set`. Non-string values are stringified. `undefined` values result in item removal. ```javascript await storage.setItem("foo:bar", "baz"); ``` ```javascript await storage.set("foo:bar", "baz"); ``` -------------------------------- ### Type Checking setItem Parameters Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Illustrates how TypeScript can be used to enforce type constraints on the values passed to `setItem` and `setItemRaw`. Incorrect types will result in compile-time errors. ```typescript storage.setItem("k", "val"); // check ok storage.setItemRaw("k", "val"); // check ok storage.setItem("k", 123); // ts error storage.setItemRaw("k", 123); // ts error ``` -------------------------------- ### hasItem / has Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Checks if storage contains a key. Resolves to either `true` or `false`. ```APIDOC ## hasItem(key, opts?) ### Description Checks if storage contains a key. ### Method `hasItem` or `has` ### Parameters #### Path Parameters - **key** (string) - Required - The key to check for. - **opts** (object) - Optional - Additional options. ### Request Example ```js await storage.hasItem("foo:bar"); await storage.has("foo:bar"); ``` ``` -------------------------------- ### Restore Data from a Snapshot Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/2.utils.md Use restoreSnapshot to populate a storage instance with data from a snapshot object previously created by the snapshot utility. An optional base path can be provided. ```javascript await restoreSnapshot(storage, { "foo:bar": "baz" }, "/etc2"); ``` -------------------------------- ### Specifying Namespace with Typed Storage Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Defines a specific structure for storage items using a type definition. This enables compile-time checks for key existence and value types within the storage instance. ```typescript type StorageDefinition = { items: { foo: string; baz: number; }; }; const storage = createStorage(); await storage.has("foo"); // Ts will prompt you that there are two optional keys: "foo" or "baz" await storage.getItem("baz"); // => string await storage.setItem("foo", 12); // TS error: is not compatible with await storage.setItem("foo", "val"); // Check ok await storage.remove("foo"); ``` -------------------------------- ### Clear Storage Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Remove all key-value pairs from the storage. If a base path is provided, only keys within that base are cleared. ```javascript await storage.clear(); ``` -------------------------------- ### Set Custom Metadata Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Set custom metadata for a key by appending a `$` suffix to the key name when using `setItem`. ```javascript await storage.setMeta("foo:bar", { flag: 1 }); // Same as storage.setItem('foo:bar$', { flag: 1 }) ``` -------------------------------- ### Set Item with Custom Headers Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/s3.md Store an item with custom HTTP headers like Content-Type and Cache-Control. This is useful for controlling how the stored data is served. ```typescript // Set Content-Type and Cache-Control await storage.setItemRaw("image.png", imageBuffer, { headers: { "Content-Type": "image/png", "Cache-Control": "max-age=31536000", }, }); ``` -------------------------------- ### setItemRaw Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Add/Update a value to the storage in raw format. Note: This is an experimental feature. ```APIDOC ## setItemRaw(key, value, opts?) ### Description Add/Update a value to the storage in raw format. If value is `undefined`, it is the same as calling `removeItem(key)`. This is an experimental feature. ### Method `setItemRaw` ### Parameters #### Path Parameters - **key** (string) - Required - The key to set. - **value** (Buffer | Array | object) - Required - The value to store in raw format. - **opts** (object) - Optional - Additional options. ### Request Example ```js await storage.setItemRaw("data/test.bin", new Uint8Array([1, 2, 3])); ``` ``` -------------------------------- ### Remove Item Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Remove a key and its associated metadata from storage using `removeItem`, `remove`, or `del`. The `removeMeta` option can be used to control metadata removal. ```javascript await storage.removeItem("foo:bar", { removeMeta: true }); // same as await storage.removeItem("foo:bar", true); ``` ```javascript await storage.remove("foo:bar"); ``` ```javascript await storage.del("foo:bar"); ``` -------------------------------- ### Strict Mode getItem Return Type Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md In strict mode, `getItem` will include `null` in its return type signature, explicitly reminding developers to handle cases where an item might not exist in the storage. ```javascript "use strict"; await storage.getItem("k"); // => ``` -------------------------------- ### Stopping All Watchers Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Stops all active watchers that have been initiated on all mount points within the storage instance. ```javascript await storage.unwatch(); ``` -------------------------------- ### Unmounting a Storage Driver Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Unregisters a previously mounted storage driver from a given mount point. This operation has no effect if the mount point is not found or if it is the root mount point. ```javascript await storage.unmount("/output"); ``` -------------------------------- ### Expire Items by Tags in Vercel Runtime Cache Source: https://github.com/unjs/unstorage/blob/main/docs/2.drivers/vercel.md Clear cache entries in the Vercel Runtime Cache based on specified tags. This allows for targeted cache invalidation. ```javascript await storage.clear("", { tags: ["user:123"] }); ``` -------------------------------- ### removeItem / remove / del Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Remove a value (and its meta) from storage. ```APIDOC ## removeItem(key, opts = { removeMeta = false }) ### Description Remove a value (and its meta) from storage. ### Method `removeItem`, `remove`, or `del` ### Parameters #### Path Parameters - **key** (string) - Required - The key to remove. - **opts** (object) - Optional - Options, defaults to `{ removeMeta: false }`. Set `removeMeta` to `true` to also remove associated metadata. ### Request Example ```js await storage.removeItem("foo:bar", { removeMeta: true }); await storage.remove("foo:bar"); await storage.del("foo:bar"); ``` ``` -------------------------------- ### removeMeta Source: https://github.com/unjs/unstorage/blob/main/docs/1.guide/1.index.md Remove meta for a specific key by adding a `$` suffix. ```APIDOC ## removeMeta(key, opts?) ### Description Remove meta for a specific key by adding a `$` suffix. This is equivalent to `storage.removeItem(key + '$')`. ### Method `removeMeta` ### Parameters #### Path Parameters - **key** (string) - Required - The key to remove meta for. - **opts** (object) - Optional - Additional options. ### Request Example ```js await storage.removeMeta("foo:bar"); ``` ```