Skip to the code

Maintenance mode with a way in for staff

Leaf and Kettle is moving its orders to a new database, and while that runs the shop must not take any. Write proxy.ts to put the site in maintenance mode. getMaintenance() from @/lib/maintenance says whether maintenance is on, and in retryAfterSeconds how long it should take. Call it on every request: staff switch maintenance on and off without a deploy.

While it's on, a page shows the maintenance page, app/maintenance/page.tsx, at its own address: rewrite to /maintenance, so the visitor can reload the same address once the shop is back.

A request to the API, /api or any path under /api/, gets its answer straight from the proxy, because the shop's app needs a status, not a page: status 503, { error: "Leaf and Kettle is down for maintenance" }, and a Retry-After header with retryAfterSeconds.

Three paths stay open: the maintenance page itself, the uptime monitor's /api/health, and the warehouse's /api/webhooks/stock, which keeps sending stock levels.

Staff need to check the real site before it reopens. A staff preview link is any address with a preview param holding STAFF_PREVIEW_TOKEN, like /teas?preview=kettle-on-7f3a9c2e. It gets a 307 redirect to the same address without preview, keeping the rest of the query, so the token leaves the address bar, and the redirect sets a maintenance-preview cookie holding the token, with path: "/", a maxAge of 8 hours in seconds, httpOnly, and sameSite: "lax". A request whose cookie holds the token goes on as normal, pages and API alike. A wrong token, in the link or the cookie, counts for nothing.

While maintenance is off, every request goes on as normal.

config.matcher must cover every page and the API, but not Next.js's own files under /_next/, which the maintenance page needs for its scripts and styles, or /favicon.ico.

GET /teas/mint          → shows /maintenance, while the address stays /teas/mint
GET /api/orders         → 503 { error: "Leaf and Kettle is down for maintenance" }   Retry-After: 1800
 
GET /teas?preview=kettle-on-7f3a9c2e&sort=price
→ 307  Location: http://localhost:3000/teas?sort=price
  and sets the cookie maintenance-preview=kettle-on-7f3a9c2e for 8 hours

The app's other files

lib/maintenance.ts, read-only. Import it as @/lib/maintenance.

/**
 * The maintenance switch, read on every request. A real shop keeps it somewhere fast to read from
 * proxy.ts, like an environment variable or an edge config store, never in the database being moved.
 */
export const maintenance = { on: true, retryAfterSeconds: 1800 };
 
/** Whether maintenance is on, and how many seconds it should take. */
export async function getMaintenance() {
  return { ...maintenance };
}
 
/** The secret in staff preview links, like /teas?preview=kettle-on-7f3a9c2e. A real app reads it from process.env. */
export const STAFF_PREVIEW_TOKEN = "kettle-on-7f3a9c2e";

What the tests check

  1. runs for pages and the API, not for Next.js's files
    for (const path of ["/", "/teas/mint", "/checkout", "/api", "/api/orders"]) expect(proxyRuns(path)).toBe(true);
    for (const path of ["/_next/static/chunks/main.js", "/_next/static/css/app.css", "/_next/image?url=%2Fimages%2Fleaf.png&w=640&q=75", "/favicon.ico"]) expect(proxyRuns(path)).toBe(false);
    
  2. while it's on, pages show the maintenance page at their own address
    for (const path of ["/", "/teas/mint?ref=mail", "/account/orders"]) {
      const response = await proxy(request(path));
      const target = response.headers.get("x-middleware-rewrite");
      expect(target && new URL(target).pathname).toBe("/maintenance");
      expect(response.headers.get("location")).toBeNull();
    }
    
  3. the API answers 503 with Retry-After
    for (const [path, method] of [["/api", "GET"], ["/api/orders", "POST"], ["/api/teas?q=mint", "GET"]]) {
      const response = await proxy(request(path, { method }));
      expect(response.status).toBe(503);
      expect(response.headers.get("retry-after")).toBe("1800");
      expect(await response.json()).toEqual({ error: "Leaf and Kettle is down for maintenance" });
    }
    maintenance.retryAfterSeconds = 600;
    expect((await proxy(request("/api/orders"))).headers.get("retry-after")).toBe("600");
    
  4. the maintenance page, the health check, and the stock webhook stay open
    // Leaving a path out of the matcher and letting it through in proxy() both work.
    for (const [path, method] of [["/maintenance", "GET"], ["/api/health", "GET"], ["/api/webhooks/stock", "POST"]]) {
      const response = proxyRuns(path) ? await proxy(request(path, { method })) : undefined;
      // NextResponse.next() marks its answer with x-middleware-next: 1; returning nothing does the same.
      expect(response === undefined ? "1" : response.headers.get("x-middleware-next")).toBe("1");
    }
    expect((await proxy(request("/api/health-report"))).status).toBe(503);
    
  5. a preview link sets the staff cookie and drops the token from the address
    const response = await proxy(request("/teas?preview=kettle-on-7f3a9c2e&sort=price"));
    expect(response.status).toBe(307);
    expect(response.headers.get("location")).toBe("http://localhost:3000/teas?sort=price");
    const cookie = response.cookies.get("maintenance-preview");
    expect(cookie?.value).toBe("kettle-on-7f3a9c2e");
    expect(cookie.path).toBe("/");
    expect(cookie.maxAge).toBe(60 * 60 * 8);
    expect(cookie.httpOnly).toBe(true);
    expect(String(cookie.sameSite).toLowerCase()).toBe("lax");
    const home = await proxy(request("/?preview=kettle-on-7f3a9c2e"));
    expect(home.headers.get("location")).toBe("http://localhost:3000/");
    
  6. staff with the cookie see the real site, and wrong tokens count for nothing
    for (const path of ["/teas/mint", "/api/orders"]) {
      const response = await proxy(request(path, { headers: { cookie: "maintenance-preview=kettle-on-7f3a9c2e" } }));
      expect(response === undefined ? "1" : response.headers.get("x-middleware-next")).toBe("1");
    }
    const wrongCookie = await proxy(request("/teas/mint", { headers: { cookie: "maintenance-preview=guess" } }));
    const cookieTarget = wrongCookie.headers.get("x-middleware-rewrite");
    expect(cookieTarget && new URL(cookieTarget).pathname).toBe("/maintenance");
    const wrongLink = await proxy(request("/teas/mint?preview=guess"));
    const linkTarget = wrongLink.headers.get("x-middleware-rewrite");
    expect(linkTarget && new URL(linkTarget).pathname).toBe("/maintenance");
    expect(wrongLink.headers.getSetCookie()).toEqual([]);
    
  7. while maintenance is off, everything goes on
    maintenance.on = false;
    for (const path of ["/teas/mint", "/api/orders", "/teas?preview=kettle-on-7f3a9c2e"]) {
      const response = await proxy(request(path));
      expect(response === undefined ? "1" : response.headers.get("x-middleware-next")).toBe("1");
      expect(response?.headers.getSetCookie() ?? []).toEqual([]);
    }
    

Learn more

proxy.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).