Recipes
View as MarkdownKill switches in Next.js
Read validated config in Next.js server components, with a timeout and defaults, and refresh it the moment you publish.
Turn on maintenance mode, show a banner or switch off a broken feature on a Next.js site without a redeploy. This recipe reads a hotcfg bin in server components, caches it with Next.js's fetch, falls back to defaults if hotcfg can't be reached, and, on Pro, refreshes the cache the moment you publish. It uses the App Router.
The config
{
"maintenance": false,
"banner": null,
"features": { "new_checkout": false }
}A schema keeps a typo from taking the site down:
{
"type": "object",
"required": ["maintenance", "features"],
"properties": {
"maintenance": { "type": "boolean" },
"banner": { "type": ["string", "null"], "maxLength": 200 },
"features": { "type": "object", "additionalProperties": { "type": "boolean" } }
}
}hotcfg bins create site-flags --schema schema.json --public
hotcfg push site-flags.json --bin site-flags --env production
hotcfg types --bin acme/site-flags --lang typescript -o lib/site-flags.tsThe last command writes the SiteFlags type from the schema. Run it again when the schema changes, and the build fails where the code reads a key that's gone. See hotcfg types.
Reading the flags
import { cache } from "react";
import type { SiteFlags } from "./site-flags";
const URL = "https://api.hotcfg.run/v1/acme/site-flags";
const DEFAULTS: SiteFlags = { maintenance: false, banner: null, features: {} };
// cache(): one fetch per render, however many components ask.
export const getFlags = cache(async (): Promise<SiteFlags> => {
try {
const res = await fetch(URL, {
cache: "force-cache",
next: { revalidate: 300, tags: ["hotcfg"] }, // refetched at most every 5 minutes, or on the webhook below
signal: AbortSignal.timeout(2000), // never hold up a page for more than 2 seconds
});
if (!res.ok) return DEFAULTS;
return { ...DEFAULTS, ...((await res.json()) as SiteFlags) };
} catch {
return DEFAULTS; // timed out or unreachable: render with the defaults
}
});Use it in any server component, layout or route handler:
import { getFlags } from "@/lib/flags";
import { Maintenance } from "@/components/maintenance";
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const flags = await getFlags();
return (
<html lang="en">
<body>
{flags.banner && <div role="status">{flags.banner}</div>}
{flags.maintenance ? <Maintenance /> : children}
</body>
</html>
);
}import { getFlags } from "@/lib/flags";
export default async function Checkout() {
const { features } = await getFlags();
return features.new_checkout ? <NewCheckout /> : <OldCheckout />;
}Within the five minutes, Next.js answers from its own cache without asking hotcfg. When it does ask, hotcfg answers from Cloudflare's edge, and keeps answering for up to a week if its servers are down, so the defaults are a last resort. To pass flags to client components, read them in a server component and pass them as props.
Refreshing on publish
On Pro, a webhook tells your site when the bin changes, so a flip shows up at once instead of within five minutes. Add a route handler that checks the signature and expires the hotcfg tag:
import { createHmac, timingSafeEqual } from "node:crypto";
import { revalidateTag } from "next/cache";
const CHANGES = new Set(["publish", "promote", "rollback", "unpublish", "rollout"]);
export async function POST(req: Request) {
const body = await req.text(); // the exact bytes hotcfg signed
if (!verifyHotcfg(body, req.headers.get("x-hotcfg-signature"), process.env.HOTCFG_WEBHOOK_SECRET ?? "")) {
return new Response("bad signature", { status: 401 });
}
const event = JSON.parse(body) as { event: string; environment: string };
if (CHANGES.has(event.event) && event.environment === "production") {
revalidateTag("hotcfg", { expire: 0 }); // the next request fetches the new config
}
return new Response(null, { status: 204 });
}
// From "Check the signature" in the webhooks guide.
function verifyHotcfg(rawBody: string, header: string | null, secret: string): boolean {
const fields = (header ?? "").split(",").map((f) => f.trim().split("="));
const t = fields.find(([k]) => k === "t")?.[1] ?? "";
const signatures = fields.filter(([k]) => k === "v1").map(([, v]) => v ?? "");
if (!secret || !/^\d+$/.test(t) || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = Buffer.from(createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex"));
return signatures.some((s) => {
const got = Buffer.from(s);
return got.length === expected.length && timingSafeEqual(got, expected);
});
}Then, in the bin's Webhooks tab, add a JSON webhook to https://your-site.example/api/hotcfg for production, and set HOTCFG_WEBHOOK_SECRET to its whsec_… secret. Press Send test: your route answers 204.
{ expire: 0 } makes the next request wait for the new config, which is what you want for a kill switch. For config where a few seconds of the old value don't matter, revalidateTag("hotcfg", "max") serves the old value once more while it fetches the new one.
Notes
- Next.js versions: this uses
fetch'snext.tagsand the two-argumentrevalidateTag, as in current Next.js. With Cache Components, put the fetch in a'use cache'function and tag it withcacheTag("hotcfg")instead. - Private bins: read from
https://private-api.hotcfg.runand addheaders: { Authorization: `Bearer ${process.env.HOTCFG_READ_KEY}` }with a publishable key limited to that bin. Keep the key in a server-side environment variable (noNEXT_PUBLIC_prefix).cache: "force-cache"caches it like any other fetch. See Reading a bin. - Staging: read
?env=stagingin preview deployments, for example by building the URL fromprocess.env.VERCEL_ENV. - Gradual rollouts: a server reads one version for everyone. To give a new version to some visitors first, pick a bucket per visitor (in a cookie) and add
?bucket=; see Progressive rollouts. - Testing failures: point
URLat?status=503or?delay=5000to check that pages still render with the defaults. See Testing slow and failing networks.
Last updated 17 November 2026