Storage
@xtandard/flags uses a pluggable storage layer. The base contract is intentionally minimal — four async methods — so anything from Redis to a database to an in-memory map satisfies it.
The FlagsStorage Contract
Section titled “The FlagsStorage Contract”import type { FlagsStorage } from "@xtandard/flags";
interface FlagsStorage { getItem<T>(key: string): Promise<T | null>; setItem<T>(key: string, value: T): Promise<void>; removeItem(key: string): Promise<void>; getKeys(prefix: string): Promise<string[]>;}All values are JSON-serializable. getItem returns null (not undefined) for missing keys. getKeys returns all keys that start with the given prefix.
Optional Capabilities
Section titled “Optional Capabilities”Adapters may implement additional interfaces that the core feature-detects at runtime:
| Interface | Extra method | Used for |
|---|---|---|
WatchableFlagsStorage |
watch(prefix, callback): Promise<() => void> |
Push-based snapshot refresh in the OpenFeature provider |
CompareAndSwapFlagsStorage |
compareAndSwap({ key, expected, next }): Promise<boolean> |
Optimistic concurrency |
TransactionalFlagsStorage |
transaction<T>(callback): Promise<T> |
Deprecated: no adapter implements it (type kept) |
The drivers come from @xtandard/kit, the shared building blocks of the xtandard products. Which
adapter has which capability:
| Adapter | watch |
compareAndSwap |
|---|---|---|
| memory, Redis / RedisJSON | ✓ | ✓ |
| file | ✓ (fs.watch) |
✓ (within one process) |
| Postgres, Drizzle, MongoDB, SQLite, libSQL | via withWatch |
✓ |
| unstorage, Cloudflare KV | via withWatch |
— |
compareAndSwap compares structurally (object key order is ignored), and values are written as
canonical JSON; rows written by earlier releases still read, list and swap.
Feature-detection helpers are exported from @xtandard/flags:
import { isWatchable, isTransactional, isCompareAndSwap } from "@xtandard/flags";
if (isWatchable(storage)) { const off = await storage.watch("flags/", (event) => console.log(event));}Official Adapters
Section titled “Official Adapters”Memory — @xtandard/flags/storage/memory
Section titled “Memory — @xtandard/flags/storage/memory”Zero dependencies. Values are deep-cloned on every read and write so mutations to returned objects do not affect stored state. Implements WatchableFlagsStorage with microtask-scheduled callbacks, and compareAndSwap.
import { createMemoryStorage } from "@xtandard/flags/storage/memory";
const storage = createMemoryStorage();
// Optionally seed with initial data:const seeded = createMemoryStorage({ initial: { "flags/projects": ["default"], },});Options:
| Option | Type | Description |
|---|---|---|
initial |
Record<string, unknown> |
Optional seed data (key → value). |
Notes: Not persistent across restarts. Ideal for tests and local development.
File — @xtandard/flags/storage/file
Section titled “File — @xtandard/flags/storage/file”Zero external dependencies (uses node:fs/promises). Each key is stored as a pretty-printed .json file, mirroring the slash-delimited key layout as a nested directory tree. Implements WatchableFlagsStorage via fs.watch on the base directory. Each key segment is encoded as a file name that stays distinct on case-insensitive file systems (macOS’s and Windows’ defaults): an uppercase letter becomes ^ + the lowercase letter (Acme → ^acme), and characters outside [a-z0-9._~!@,=+-] become %XX. An empty segment (a//b) is a lone %, so it stays a distinct key. Lowercase keys (flags/default/production/…) map to themselves. Writes go to a temporary file that is renamed into place, so a crash never leaves a half-written value, and compareAndSwap is serialized per key within one process (several processes sharing one directory need a database adapter).
Files written before the encoding (flags/MyProject/…) are still read and listed (legacy: "read-through", the default), and are replaced by their encoded name on the next write or remove. To convert a whole tree at once, run migrateFileStorage({ dir }) (exported from this subpath; idempotent, run it with no writer). Pass legacy: "ignore" to skip legacy files entirely.
import { createFileStorage } from "@xtandard/flags/storage/file";
const storage = createFileStorage({ dir: "./data/flags" });Options:
| Option | Type | Description |
|---|---|---|
dir |
string |
Base directory. Created on demand. |
legacy |
"read-through" | "warn" | "ignore" |
Files in the pre-encoding layout. Default "read-through". |
Key layout on disk:
./data/flags/ flags/ default/ production/ active_version.json draft.json snapshots/ v1.json v2.json audit/ v1.jsonNotes: watch is best-effort; recursive watch support varies by platform. Useful for GitOps workflows where the data directory lives in version control.
Redis — @xtandard/flags/storage/redis
Section titled “Redis — @xtandard/flags/storage/redis”Requires redis (node-redis v4 or v5) as a peer dependency. Lazy connection: the client connects on the first operation. Uses non-blocking SCAN cursors for getKeys (never KEYS). Implements WatchableFlagsStorage via Redis keyspace notifications.
import { createRedisStorage } from "@xtandard/flags/storage/redis";
// Connect by URL:const storage = createRedisStorage({ url: "redis://localhost:6379", prefix: "myapp:flags:source",});
// Or pass a pre-connected client:import { createClient } from "redis";const client = createClient({ url: process.env.REDIS_URL });await client.connect();
const storage = createRedisStorage({ client, prefix: "myapp:flags" });
// Disconnect when done:await storage.close();Options:
| Option | Type | Description |
|---|---|---|
url |
string |
Redis connection URL. Used when no client is provided. |
client |
RedisClientType |
Pre-constructed node-redis client. |
prefix |
string |
Namespace prepended to every key with a : separator. Stripped from keys returned by getKeys. |
The adapter exposes a close() method that disconnects the client it created. If you supplied a client, close() is a no-op and you manage the connection yourself.
Watch prerequisite: Redis must be configured with keyspace notifications that cover generic and string events. The minimum recommended setting:
notify-keyspace-events KEAWithout this, watch calls will silently receive no events and the provider falls back to polling only.
Values are plain strings containing JSON — by design. Every value (snapshot, draft, audit log) is read/written as a whole document, so SET/GET is the natural, atomic mapping. If you want the stored data to be queryable inside Redis, use the JSON variant below.
createRedisJSONStorage — native RedisJSON documents
Section titled “createRedisJSONStorage — native RedisJSON documents”Same options, plumbing (lazy connect, SCAN, keyspace-notification watch, close), and behavior — but values are stored with JSON.SET/JSON.GET as native JSON documents, so snapshots/drafts are queryable with JSONPath and indexable with RediSearch:
import { createRedisJSONStorage } from "@xtandard/flags/storage/redis";
const storage = createRedisJSONStorage({ url: process.env.REDIS_URL, prefix: "myapp:flags" });# then, in redis-cli — query a published snapshot directly:JSON.GET myapp:flags:flags/default/production/snapshots/v1 $.flags.new-checkout.enabled# → [true]Requirements & caveats:
- The server needs the JSON module: built into Redis 8, or Redis Stack /
redisjsonloaded. (The client side is free — node-redis bundles thejson.*commands.) - Never point both variants at the same keys — a string value and a RedisJSON value are different Redis types; reading one with the other fails with
WRONGTYPE. Migrating an existing deployment means a fresh prefix (or re-publishing). watchworks the same;KEAcovers the module events RedisJSON writes emit (e.g.json.set).
Unstorage — @xtandard/flags/storage/unstorage
Section titled “Unstorage — @xtandard/flags/storage/unstorage”Wraps any unstorage Storage instance. You choose and configure the unstorage driver; this adapter normalises its API to FlagsStorage. No built-in watch — wrap it with withWatch if you have a change source, or use the Redis/file adapter for out-of-the-box push notifications. unstorage normalizes keys lossily (it cuts at ? and treats \ and : as separators), so the adapter escapes %, ?, \ and : before handing keys over and reverses it when listing: keys round-trip exactly. File-system unstorage drivers inherit their file system’s case sensitivity; prefer the file adapter, which encodes case.
import { createUnstorageStorage } from "@xtandard/flags/storage/unstorage";import { createStorage } from "unstorage";import redisDriver from "unstorage/drivers/redis";
const storage = createUnstorageStorage({ storage: createStorage({ driver: redisDriver({ url: process.env.REDIS_URL }), }),});Options:
| Option | Type | Description |
|---|---|---|
storage |
Storage |
A pre-constructed unstorage Storage instance (any driver). |
Notes: unstorage normalizes key separators to : internally. The adapter converts them back to / so callers always see the keys they wrote. The unstorage package must be installed as a peer dependency.
Source vs Runtime Guidance
Section titled “Source vs Runtime Guidance”| Mode | Source | Runtime | When to use |
|---|---|---|---|
| Simple | any | same (default) | Local dev, all-in-one single node |
| Dev | memory | memory | Tests, in-process experiments |
| Production | Redis source prefix | Redis runtime prefix | Separate stores for isolation |
| GitOps | file storage | file or Redis | Draft files in VCS, CI publishes |
For production, separate the two stores so the runtime store (read by every application instance) is not in the same logical namespace as the admin draft and audit data. Using separate Redis prefixes (myapp:flags:source and myapp:flags:runtime) achieves this without needing two Redis clusters.
Choosing a backend
Section titled “Choosing a backend”| Backend | Adapter | Runtime | Best for |
|---|---|---|---|
| Memory | storage/memory |
any | tests, single-process experiments |
| File | storage/file |
any | local dev, GitOps drafts in VCS |
| Redis | storage/redis |
any | multi-node, push-based refresh (watch) |
| Redis (JSON) | storage/redis (createRedisJSONStorage) |
any | same, plus JSONPath/RediSearch-queryable data (needs the JSON module: Redis 8 / Stack) |
| Postgres | storage/postgres |
any | you already run Postgres; transactional source |
| Drizzle | storage/drizzle |
any | you use Drizzle — table in your migrations, your pool |
| MongoDB | storage/mongodb |
any | you already run Mongo |
| SQLite | storage/sqlite |
Bun | single-node persistence, zero deps |
| libSQL / Turso | storage/libsql |
any / edge | edge-replicated runtime, serverless SQLite |
| Cloudflare KV | storage/cloudflare-kv |
Workers | runtime snapshots inside Cloudflare Workers |
| Anything else | storage/unstorage |
any | 20+ drivers (Upstash, Vercel KV, S3/R2, Netlify, …) |
A common production split is a durable, transactional source (Postgres/Redis) plus a fast, close-to-the-app runtime (Redis/libSQL/KV). See the storage-combo examples.