DEV Community

Daniel Pertu
Daniel Pertu

Posted on

Our maintenance switch is one boolean, and the page it shows answers 200 because a rewrite cannot carry a 503

Munchable is one Next.js app doing two jobs. Half of it is the backend for a phone app: you scan a barcode in a shop and get an answer about whether that product suits your gut. The other half is a content site, and it is much bigger than it sounds. There are 516 URLs in the sitemap, and every single one of them renders from data committed in the repo. No database, no session, no user.

So when I needed planned downtime for the first time, the usual shape of a maintenance page was wrong. The usual shape is a flag on the edge and a single page for every request. That would have taken down the recipe library, the condition guides and 461 generated answer pages, none of which have any idea that a database exists.

What shipped is 41 lines in one file, plus a branch at the top of the proxy.

The switch is a boolean, and the annotation is the interesting part

// Typed as boolean, not the literal, so both settings typecheck the same way.
export const MAINTENANCE: boolean = false;
Enter fullscreen mode Exit fullscreen mode

That annotation is doing real work. Write export const MAINTENANCE = false and TypeScript infers the literal type false, not boolean. Every if (MAINTENANCE) body becomes code the compiler knows is unreachable, every comparison against true becomes an error about a condition that will always return false, and the day you flip it to true the errors move to the other half of the codebase. You would be editing one line and fixing twelve.

With the annotation, both values typecheck identically, which means the flip is genuinely one character of diff and a deploy.

There is no environment variable. That is a deliberate trade: an env var is faster to flip, but it is also a thing whose value you cannot read in a diff, cannot test, and cannot see in a code review. Downtime here is planned, I am the person planning it, and a commit is a better record of "the site was off between these two deploys" than a dashboard toggle nobody logged.

Three kinds of path, five prefixes

The whole routing decision is one function:

const APP_PREFIXES = ['/admin', '/auth', '/continue', '/get-started', '/support'];

export type MaintenanceRoute = 'api' | 'app' | 'public';

export function maintenanceRoute(pathname: string): MaintenanceRoute {
  if (pathname === '/api' || pathname.startsWith('/api/')) return 'api';
  const isApp = APP_PREFIXES.some(
    (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),
  );
  return isApp ? 'app' : 'public';
}
Enter fullscreen mode Exit fullscreen mode

Five prefixes cover every page that needs the database, a session, or sign in: the admin panel, the OAuth callback, the app to web handoff, the sign in page, and the support ticket pages. Ten page routes in total. Everything else outside /api is content, and content stays up.

Note the shape of the prefix test. It is not startsWith(prefix), it is "equals the prefix, or starts with the prefix plus a slash". Without that, /administration is an admin page and /supported is a support page. There is a test whose only job is to assert that four such paths stay public, because this is exactly the kind of thing that is obviously right when you write it and silently wrong after somebody adds a marketing page called /authors.

The API answers 503, including the parts with no browser

All 29 API routes get the same answer:

const response = NextResponse.json(
  { error: 'maintenance', message: MAINTENANCE_MESSAGE },
  { status: 503, headers: { 'Retry-After': String(MAINTENANCE_RETRY_AFTER_SECONDS) } },
);
return applyCorsHeaders(request, response);
Enter fullscreen mode Exit fullscreen mode

Three things in there were not obvious to me beforehand.

CORS headers still get stamped on the refusal. In normal operation the proxy owns CORS for /api/* and no route handler emits those headers itself. If maintenance returns early and skips that, then the phone app does not get "the server is down for maintenance", it gets a CORS error in a catch block, which it will report to the user as a network failure. The refusal has to be readable by the thing being refused.

Retry-After: 300 is a real promise, not decoration. It is the one piece of the refusal a client can act on without parsing anything.

And the webhook routes, which are normally waved straight through the proxy because they are server to server and signature verified, are matched by the proxy config only so that maintenance can refuse them too. There is a comment in proxy.ts saying so, because otherwise the matcher looks like it is doing nothing for them.

Same for the two cron jobs. They are at /api/cron/*, so they get the 503, and the platform does not retry a missed cron run. The maintenance file says what to do about that:

// Cron runs refused in the window are not retried. If it covers the monthly
// rewards settlement (04:00 UTC on the 8th), run that by hand afterwards.
Enter fullscreen mode Exit fullscreen mode

The hourly job is fine: it is a fingerprint diff that will pick up everything it missed on the next run. The monthly one moves money and only fires on the 8th. Writing that down next to the switch, rather than in a runbook, is the only version of this I actually trust, because the person flipping the switch is the person who will forget.

The page that cannot tell you its own status

Pages in the app group get a rewrite:

if (route === 'app') return NextResponse.rewrite(new URL(MAINTENANCE_PATH, request.url));
Enter fullscreen mode Exit fullscreen mode

A rewrite keeps the URL. If you were on /support/01J... and you reload during the window, you stay on /support/01J... and see the maintenance card. When the window ends, a reload puts you back on your ticket. A redirect would have thrown that URL away and dumped everybody on /maintenance.

The cost is the status code. Next drops the status of a proxy rewrite and serves the destination page's own, so those pages answer 200 OK while showing a page that says the site is down. There is no NextResponse.rewrite(url, { status: 503 }) that works here. You can have the URL or you can have the status code.

I kept the URL, because the audience for these ten pages is a signed-in human who wants to come back to where they were, not a crawler. The 516 pages a crawler actually cares about are all still answering 200 with their real content, which is the only reason that trade is cheap. If the content pages had been in the app group too, I would have made the opposite choice and taken the redirect.

The maintenance page itself then has two deliberate absences:

/**
 * No canonical and no robots override, deliberately: this renders at other
 * pages' URLs (/support among them), so either would be read as being about
 * that page. A noindex here would ask for /support to be dropped from the index.
 */
Enter fullscreen mode Exit fullscreen mode

A noindex on a page that renders at somebody else's URL is not a statement about the maintenance page. It is a statement about /support. Same for a canonical. The page has a title and a description and nothing else.

And it refuses to render when there is nothing to report:

export default function Maintenance() {
  if (!MAINTENANCE) redirect('/get-started');
Enter fullscreen mode Exit fullscreen mode

So munchable.app/maintenance is not a page you can visit today. The only way to see it is to turn the switch on, which means the page cannot drift out of sync with the thing it describes.

The client half, which is a loading state

The sign in controls in the header read the same constant. The interesting line is the initial state of the auth hook:

const [ready, setReady] = useState(MAINTENANCE);

useEffect(() => {
  if (MAINTENANCE) return;
  ...
Enter fullscreen mode Exit fullscreen mode

ready normally starts false and flips true when Supabase answers with a session. During maintenance no session is ever fetched, so starting it false would leave the header spinner going forever. Starting it at the value of the switch means the UI is immediately in its settled, signed out state, and the sign in button explains itself instead of hanging. Sign in is also refused client side with the same message string, so nothing calls the auth provider at all during the window.

One string, MAINTENANCE_MESSAGE, is what the header says, what the API returns in JSON, and what the page prints. Three surfaces, one sentence, which is the only way all three stay in agreement about how long "a little while" is.

What this cost

41 lines of switch, a 15 line branch in the proxy, a 47 line page, and four tests. The tests are the kind I like: they assert that specific real paths land in the right bucket, including /api/webhook/stripe, /api/cron/indexnow, /premium/success, /sitemap.xml and one of the generated answer pages.

The thing I would tell anyone adding this to a similar app: decide first how much of your site actually needs the database. If the answer is "most of it", a flag at the edge and one page is correct and you are done in ten minutes. If your app is a content site wearing an API as a hat, the split is worth the extra half hour, because the pages that stay up are the ones strangers arrive on.

Have a look at what survives the window: the gluten vocabulary reference, a recipe, the coeliac disease guide, about, privacy and terms. None of them will notice.

Top comments (0)