StackKit

A Signed-Cookie Admin Login in Next.js Without a Database, and Its Limits

By · · 7 min read

This blog has a small admin panel for editing articles and reading the crawler log. I didn't want a user table, an auth library and a session store for one person, so I built the login with a signed cookie and Node's built-in crypto. It works, but it has real limits, and I'll point them out so you can decide whether the same shortcut is right for your project.

The design

  • One admin account, defined by three environment variables: ADMIN_USERNAME, ADMIN_PASSWORD, ADMIN_SECRET.
  • Logging in sets an HTTP-only cookie containing an HMAC signature.
  • The proxy checks that cookie before any /admin route renders.
  • If any of the three variables is missing, login is simply disabled.

The auth module

import { createHmac, timingSafeEqual } from "node:crypto";

export const COOKIE_NAME = "sk_admin_session";

export function adminConfig() {
  const username = process.env.ADMIN_USERNAME;
  const password = process.env.ADMIN_PASSWORD;
  const secret = process.env.ADMIN_SECRET;
  if (!username || !password || !secret) return null;
  return { username, password, secret };
}

function sign(secret: string, username: string): string {
  return createHmac("sha256", secret).update(`admin:${username}`).digest("hex");
}

adminConfig() returns null unless all three variables exist. That is a safe default: a fresh deploy without secrets can't be logged into, instead of falling back to a default password.

Comparing credentials safely

export function checkCredentials(username: string, password: string): boolean {
  const cfg = adminConfig();
  if (!cfg) return false;
  const a = Buffer.from(`${username}\0${password}`);
  const b = Buffer.from(`${cfg.username}\0${cfg.password}`);
  return a.length === b.length && timingSafeEqual(a, b);
}

Using === on secrets can leak information through timing differences, because it stops at the first mismatching character. timingSafeEqual takes the same time regardless of where the strings differ. Two things to notice:

  • timingSafeEqual throws if the two buffers have different lengths, so the length is checked first. That check does reveal the length of the real credentials to someone measuring carefully, which is a small, accepted leak for a single-admin tool.
  • The username and password are joined with a \0 byte so ("ab", "c") can't equal ("a", "bc").

The login route

The route reads the body, checks the credentials, and sets the cookie:

res.cookies.set(COOKIE_NAME, token, {
  httpOnly: true,
  secure: process.env.NODE_ENV === "production",
  sameSite: "lax",
  maxAge: 60 * 60 * 24 * 7, // 7 days
  path: "/",
});
  • httpOnly keeps JavaScript from reading the cookie, which limits what an XSS bug can steal.
  • secure in production means the cookie is only sent over HTTPS.
  • sameSite: "lax" blocks the cookie on cross-site POST requests, which covers the common CSRF case.
export function verifySessionToken(token: string | undefined): boolean {
  const expected = createSessionToken();
  if (!token || !expected) return false;
  const a = Buffer.from(token);
  const b = Buffer.from(expected);
  return a.length === b.length && timingSafeEqual(a, b);
}

and in proxy.ts:

if (pathname.startsWith("/admin")) {
  if (!pathname.startsWith("/admin/login") && !verifySessionToken(req.cookies.get(COOKIE_NAME)?.value)) {
    return NextResponse.redirect(new URL("/admin/login", req.url));
  }
  return NextResponse.next();
}

The proxy runs before the page, so unauthenticated visitors are redirected before any admin code runs.

The honest limitations

This design is simple partly because it skips things a real session system has:

  1. The token is the same every time. It's HMAC(secret, "admin:<username>"), with no random value and no timestamp. Every login for the same user produces an identical token. The cookie's 7-day maxAge is enforced by the browser only; if someone copied the token, the server would accept it forever, until you change ADMIN_SECRET.
  2. No logout on the server. The logout route can delete the cookie in your browser, but it can't invalidate a copied token.
  3. No rate limiting on login. Someone can try passwords as fast as the server answers. A long random password makes this impractical, but a limiter would be better.
  4. One user only. Fine here, not fine for a team.

When this is acceptable, and what I'd change

For a one-person admin panel behind HTTPS with a long random password, I consider this reasonable. If it grew, I'd fix the first limitation by putting an expiry timestamp inside the signed value (username.expiresAt.signature) and verifying the timestamp too. That keeps the "no database" property and makes tokens expire on the server side.

If more than one person needed access, I'd stop here and use a maintained auth library instead of extending this.