Skip to the code

Password-protect the staging site

Before each release, Leaf and Kettle's team tries the shop out on a staging copy. Search engines and curious customers must not find it, so the whole staging site goes behind HTTP Basic authentication: the browser asks for a user name and password once, then sends them with every request. Write proxy.ts.

The browser sends Authorization: Basic <credentials>, where the credentials are user:password in base64. The scheme name, Basic, may come in any case. Decode the credentials with atob, which throws for text that isn't base64. The user name is everything before the first colon and the password everything after it, so a password may contain colons. The right ones are STAGING_USER and STAGING_PASSWORD in @/lib/staging; compare them with its safeEqual(a, b).

With the right user name and password, let the request through with NextResponse.next(). Anything else gets an answer straight from proxy.ts: status 401, the text Authentication required, and the header WWW-Authenticate: Basic realm="Leaf and Kettle staging", which makes the browser show its sign-in box. That covers a missing header, another scheme like Bearer, credentials that don't decode or have no colon, and a wrong user name or password.

The uptime monitor checks /api/health every minute and has no password, so that one path needs none. Every other request does, Next.js's own scripts under /_next/ and the files in public too.

GET /teas                                          (no Authorization header)
→ 401 Authentication required
  WWW-Authenticate: Basic realm="Leaf and Kettle staging"
 
GET /teas   Authorization: Basic dGVzdGVyOnN0ZWVwOjQtbWludXRlcw==
→ goes on to the page (that's tester:steep:4-minutes)

The app's other files

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

/** The staging site's user name and password. A real app reads them from process.env, on the server only. */
export const STAGING_USER = "tester";
export const STAGING_PASSWORD = "steep:4-minutes";
 
/** Whether `a` and `b` are the same text, in the same time wherever they differ. */
export function safeEqual(a: string, b: string): boolean {
  if (a.length !== b.length) return false;
  let difference = 0;
  for (let i = 0; i < a.length; i++) difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return difference === 0;
}

What the tests check

  1. asks for a password with a 401 and WWW-Authenticate
    const response = await proxy(request("/teas"));
    expect(response.status).toBe(401);
    expect(response.headers.get("www-authenticate")).toBe('Basic realm="Leaf and Kettle staging"');
    expect(await response.text()).toBe("Authentication required");
    
  2. lets the right user name and password through, colons and all
    for (const scheme of ["Basic", "basic", "BASIC"]) {
      const response = await proxy(request("/teas/mint", { headers: { authorization: scheme + " " + btoa("tester:steep:4-minutes") } }));
      // 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");
    }
    
  3. a wrong user name or password gets a 401
    for (const pair of ["tester:steep", "tester:steep:4-minutes:", "Tester:steep:4-minutes", "admin:steep:4-minutes", ":tester:steep:4-minutes", "tester:"]) {
      const response = await proxy(request("/teas", { headers: { authorization: "Basic " + btoa(pair) } }));
      expect(response.status).toBe(401);
      expect(response.headers.get("www-authenticate")).toBe('Basic realm="Leaf and Kettle staging"');
    }
    
  4. other schemes and broken credentials get a 401, not an error
    for (const authorization of ["Bearer token-ana", "Basic", "Basic !!!not-base64!!!", "Basic " + btoa("tester"), "tester:steep:4-minutes"]) {
      const response = await proxy(request("/teas", { headers: { authorization } }));
      expect(response.status).toBe(401);
      expect(response.headers.get("www-authenticate")).toBe('Basic realm="Leaf and Kettle staging"');
    }
    
  5. the uptime monitor's /api/health needs no password
    // Leaving it out of the matcher and letting it through in proxy() both work.
    const response = proxyRuns("/api/health") ? await proxy(request("/api/health")) : undefined;
    expect(response === undefined ? "1" : response.headers.get("x-middleware-next")).toBe("1");
    expect(proxyRuns("/api/health-report")).toBe(true);
    expect((await proxy(request("/api/health-report"))).status).toBe(401);
    
  6. every other request needs the password, Next.js's files too
    for (const path of ["/", "/teas/mint", "/api/orders/1002", "/_next/static/chunks/main.js", "/images/leaf.png", "/favicon.ico"]) {
      expect(proxyRuns(path)).toBe(true);
      expect((await proxy(request(path))).status).toBe(401);
    }
    

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).