Nitro has built-in integration with unstorage to provide a runtime agnostic persistent layer.
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")
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.
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.
In scenarios where the mount point configuration is not known until runtime, Nitro can dynamically add mount points during startup using plugins.
import { useStorage } from "nitro/storage";
import { definePlugin } from "nitro";
import redisDriver from "unstorage/drivers/redis";
export default definePlugin(() => {
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)
})