Skip to content
SecurityChapter 37 / 57Intermediate6 min read

Security Baseline

A web security checklist with headers, hashed tokens, timing safe comparison, fail closed auth, a CORS allow-list and the minimum standard for uploads.

On this page

1. What is this practice?

Baseline does not mean "the best possible security". It means the floor that no project goes below. Advanced things come later, but this list applies from day one.

This chapter is a checklist. Each item has its own deeper chapter, like Secrets Management and Input Validation at the Boundary.

2. Why does it matter?

Security breaches usually do not come from fancy hacks, they come from forgotten basics. An audit often finds that every item is broken in some repo, so treat the baseline as a checklist, not an aspiration.

Without a baselineWith a baseline
Request allowed when the secret is missing503 when the secret is missing, nothing allowed
Session tokens stored in plain text in the databaseOnly the hash is stored, so a leak is useless
Secret compared with ===Timing safe comparison
Any website can call the API with credentialsCORS allows only our own origins
Stack trace and SQL in the errorThe caller gets only the needed message, details go to logs
Upload name and type are the user's choiceMagic bytes check, size cap, random key

3. When to follow it

LevelHow importantWhy
Learning projectSecrets, validation and fail closed at leastThese same habits carry into production later
Production codeThe whole listOne weak item is a door into the whole system
Senior levelPut the list into CI and templatesEvery new repo gets the baseline automatically, nobody has to remember

4. Bad vs good code

Bad: fail open and a direct comparison

ts
export async function GET(request: Request) {
  const secret = process.env.CRON_SECRET;
  if (secret && request.headers.get("authorization") !== `Bearer ${secret}`) {
    return new Response("unauthorized", { status: 401 });
  }
  await sendDailyEmails();
  return Response.json({ ok: true });
}

Two problems: if the secret is missing the check is skipped entirely, and !== stops at the first mismatch, which makes it possible to guess the secret through timing.

Good: fail closed and timing safe

ts
import { createHash, timingSafeEqual } from "node:crypto";

function digest(value: string) {
  return createHash("sha256").update(value).digest();
}

function safeEqual(received: string, expected: string) {
  return timingSafeEqual(digest(received), digest(expected));
}

export async function GET(request: Request) {
  const secret = process.env.CRON_SECRET;
  if (!secret) {
    return new Response("not configured", { status: 503 });
  }

  const header = request.headers.get("authorization") ?? "";
  if (!safeEqual(header, `Bearer ${secret}`)) {
    return new Response("unauthorized", { status: 401 });
  }

  await sendDailyEmails();
  return Response.json({ ok: true });
}

Hashing both values makes their lengths equal, which is a requirement of timingSafeEqual.

Security headers (Next.js)

ts
import type { NextConfig } from "next";

const securityHeaders = [
  { key: "X-Content-Type-Options", value: "nosniff" },
  { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
  { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
  { key: "X-Frame-Options", value: "DENY" },
  { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains" },
  { key: "Content-Security-Policy", value: "default-src 'self'; frame-ancestors 'none'" },
];

const nextConfig: NextConfig = {
  async headers() {
    return [{ source: "/:path*", headers: securityHeaders }];
  },
};

export default nextConfig;

What is the difference?

ThingBadGood
Missing secretEndpoint open503, nothing runs
Comparison!==, timing leaktimingSafeEqual after hashing
HeadersBrowser defaultsClickjacking, sniffing and referrer leaks closed

5. How to apply it

This checklist applies to every repo:

AreaMinimum
SecretsNothing committed, .env.example present, scanner on
TokensSession tokens, login codes, magic links and API keys stored hashed, only the hash compared
ComparisonsEvery shared secret checked with timingSafeEqual
AuthFail closed: deny if a secret or config is missing
Test bypassRefused in production, checked in middleware, and covered by a test
HeadersCSP, nosniff, Referrer-Policy, Permissions-Policy, frame protection, HSTS
CORSAn explicit origin allow-list, never "every origin + credentials"
InputSchema validation at every boundary, no interpolation into SQL, shell or HTML
UploadsMagic bytes check, size cap, random key, served through an opaque proxy route
ErrorsLittle for the caller, detail in the logs
LoggingScrub secrets and personal data, no URLs with query strings in production
If you find a leak or an auth bypass
Stop feature work
Rotate or fix it
Tell the team the same day: what, when, what was rotated

6. Exceptions and common mistakes

When the rule does not apply: public, read-only endpoints (like a list of blog posts) do not need auth, but they still need validation, rate limiting and headers. In CSP you may have to keep 'unsafe-inline' at first. Treat that as a step toward the goal, and move toward nonces.

Mistake: Reflecting every origin in CORS and allowing credentials

Why? This lets any website call your API with the user's cookies.

Better: Keep an explicit list of allowed origins and allow credentials only for those.

Mistake: Recognizing an upload by its file extension

Why? The user can change the extension and send a script disguised as an image.

Better: Check the file's first bytes (magic bytes), apply a size cap, and store it under a random name.

Mistake: A test bypass token that also works in production

Why? This is a backdoor with a friendly name.

Better: Have the middleware refuse it in production, and prove that with a unit test.

Mistake: Giving the user a raw bucket URL

Why? If the URL is shared or guessed, the file is open forever and the access check is bypassed.

Better: Serve it through a proxy route that checks access on every request.

7. What to learn before and after

Final quick revision

CheckYes?
Tokens hashed, only the hash compared
Shared secrets checked with timingSafeEqual
503 on missing config, never allow
Security headers set
CORS has an explicit allow-list
Uploads: magic bytes, size cap, random key
No internal detail in errors