diff --git a/docs/1.docs/8.storage.md b/docs/1.docs/8.storage.md index f1d3fc750b..a21aae3ac2 100644 --- a/docs/1.docs/8.storage.md +++ b/docs/1.docs/8.storage.md @@ -101,6 +101,67 @@ Then, you can use the redis storage using the `useStorage("redis")` function. You can find the driver list on [unstorage documentation](https://unstorage.unjs.io/) with their configuration. :: +### Custom drivers + +The `driver` field accepts a built-in driver name (for example `"redis"`) or a **path** to a custom driver module. You cannot pass a driver function or object directly in config — Nitro imports drivers as separate modules so your config stays separate from runtime code. + +Create a driver file that **default-exports** a driver factory from `defineDriver`. To build a driver from scratch, implement the [unstorage driver interface](https://unstorage.unjs.io/guide/custom-driver) (`hasItem`, `getItem`, `setItem`, and so on): + +```ts [drivers/kv.ts] +import { defineDriver } from "unstorage"; + +export default defineDriver((opts: { prefix?: string } = {}) => { + const data = new Map(); + const prefix = opts.prefix || ""; + + return { + name: "kv", + options: opts, + hasItem(key) { + return data.has(prefix + key); + }, + getItem(key) { + return data.get(prefix + key) ?? null; + }, + setItem(key, value) { + data.set(prefix + key, value); + }, + removeItem(key) { + data.delete(prefix + key); + }, + getKeys() { + return [...data.keys()].map((k) => + prefix ? k.slice(prefix.length) : k, + ); + }, + clear() { + data.clear(); + }, + }; +}); +``` + +Reference it by path in your Nitro config (options besides `driver` are passed into the factory): + +```ts [nitro.config.ts] +import { defineConfig } from "nitro"; + +export default defineConfig({ + storage: { + kv: { + driver: "./drivers/kv.ts", + prefix: "app:", + }, + }, +}); +``` + +Use a path relative to your project root (or an absolute path). Nitro bundles the driver for the server runtime. + +To **patch** an existing unstorage driver instead of writing one from scratch, wrap it inside `defineDriver`, spread the base driver, and override only the methods you need. + +:read-more{to="https://unstorage.unjs.io/guide/custom-driver" title="unstorage custom driver guide"} + ### Development storage You can use the `devStorage` option to override storage configuration during development and prerendering.