Skip to content

The fetch handler and custom adapters

createFetchHandler — The Underlying Primitive

Section titled “createFetchHandler — The Underlying Primitive”

All adapters call createFetchHandler internally. Use it directly to build your own adapter:

import { createFetchHandler, type FlagsPanelOptions } from "@xtandard/flags";
const { fetch, core } = createFetchHandler({
sourceStorage,
runtimeStorage,
basePath: "/flags",
auth,
authorization,
readonly: false,
title: "My Flags",
});

fetch(request: Request): Promise<Response> is a web-standard handler ready to be passed to any framework.


Writing a Thin Adapter for Any Fetch-Based Framework

Section titled “Writing a Thin Adapter for Any Fetch-Based Framework”

Node’s http.IncomingMessage is not a web Request, but you can bridge it:

import express from "express";
import { createFetchHandler } from "@xtandard/flags";
const { fetch: panelFetch } = createFetchHandler({ sourceStorage, basePath: "/flags" });
const app = express();
app.use("/flags", (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const webRequest = new Request(url.toString(), {
method: req.method,
headers: req.headers as HeadersInit,
body: ["GET", "HEAD"].includes(req.method) ? undefined : req,
});
panelFetch(webRequest).then((response) => {
res.status(response.status);
response.headers.forEach((value, key) => res.setHeader(key, value));
response.body
? response.body
.pipeTo(
new WritableStream({
write: (chunk) => {
res.write(chunk);
},
}),
)
.then(() => res.end())
: res.end();
});
});
app/flags/[[...slug]]/route.ts
import { createFetchHandler } from "@xtandard/flags";
import { createRedisStorage } from "@xtandard/flags/storage/redis";
const { fetch: panelFetch } = createFetchHandler({
sourceStorage: createRedisStorage({ url: process.env.REDIS_URL!, prefix: "app:flags:source" }),
basePath: "/flags",
});
export const GET = panelFetch;
export const POST = panelFetch;
export const PUT = panelFetch;
export const DELETE = panelFetch;

Any runtime that accepts (Request) => Response | Promise<Response> can use createFetchHandler directly — the return value is exactly that shape.