KV Storage
Nitro provides a built-in storage layer that can abstract filesystem or database or any other data source.
Nitro v3 Alpha docs are a work in progress — expect updates, rough edges, and occasional inaccuracies.
Nitro has built-in integration with unstorage to provide a runtime agnostic persistent layer.
Usage
To use the storage layer, you can use the useStorage() and call get(key) to retrieve an item and set(key, value) to set an item.
import { useStorage } from "nitro/storage";
// Default storage is in memory
await useStorage().set("test:foo", { hello: "world" })
await useStorage().get("test:foo")
// You can use data storage to write data to default .data/kv directory
const dataStorage = useStorage("data")
await dataStorage.set("test", "works")
await dataStorage.get("data:test") // Value persists
// You can also specify the base in useStorage(base)
await useStorage("test").set("foo", { hello: "world" })
// You can use generics to define types
await useStorage<{ hello: string }>("test").get("foo")
await useStorage("test").get<{ hello: string }>("foo")
Configuration
You can mount one or multiple custom storage drivers using the storage option.
The key is the mount point name, and the value is the driver name and configuration.
nitro.config.ts
import { defineNitroConfig } from "nitro/config";
export default defineNitroConfig({
storage: {
redis: {
driver: "redis",
/* redis connector options */
}
}
})
Then, you can use the redis storage using the useStorage("redis") function.
You can find the driver list on unstorage documentation with their configuration.
Runtime configuration
In scenarios where the mount point configuration is not known until runtime, Nitro can dynamically add mount points during startup using plugins.
plugins/storage.ts
import { defineNitroPlugin, useStorage } from "nitro/storage";
import redisDriver from "unstorage/drivers/redis";
export default defineNitroPlugin(() => {
const storage = useStorage()
// Dynamically pass in credentials from runtime configuration, or other sources
const driver = redisDriver({
base: "redis",
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
/* other redis connector options */
})
// Mount driver
storage.mount("redis", driver)
})
This is a temporary workaround, with a better solution coming in the future! Keep a lookout on the GitHub issue here.