Nov 18, 20266 min read

How to Add API Key Authentication to a Backend API

Design API keys that are safe to store and easy to rotate: prefixed random keys, hashed at rest, looked up by a public prefix, scoped and revocable, with a TypeScript implementation by hand and as an Encore auth handler.

Illustration for How to Add API Key Authentication to a Backend API

API keys are the authentication most backend APIs offer first, because machine-to-machine callers such as scripts, integrations and other backends cannot go through a login page.

The first version is usually a random string in a column and a WHERE key = $1 lookup, which means the database holds every customer's live credential in plain text, nobody can tell which key a request used, and rotating one means an outage for that customer.

This guide designs keys that avoid those problems, then implements the check as Express middleware and as an Encore auth handler.

API key design at a glance

DecisionRecommendationWhy
Formatsk_live_ prefix plus 32 random bytes, base62 or base64urlPrefix makes leaks searchable and keys recognizable
StorageSHA-256 hash of the key, plus a short public prefixA database leak does not leak working keys
LookupBy public prefix or key ID, then compare hashes in constant timeAvoids timing differences and full-table scans
TransportAuthorization: Bearer <key> over HTTPSQuery strings end up in logs and browser history
ScopePer-key scopes and an owning accountIntegrations get only the access they need
LifecycleSeveral active keys per account, last_used_at, revoke and expireRotation without downtime

Generate keys with a prefix

Generate keys from a cryptographically secure source and give them a recognizable prefix. A prefix like sk_live_ tells support which environment a key belongs to, and it lets secret scanners find leaked keys: GitHub's secret scanning partner program matches provider patterns in pushed code and notifies the issuer. Keep the first few characters after the prefix as a public identifier that you can show in the dashboard and use for lookup.

import { randomBytes, createHash, timingSafeEqual } from "node:crypto"; export function newApiKey() { const secret = randomBytes(32).toString("base64url"); const key = `sk_live_${secret}`; return { key, // shown to the customer once prefix: key.slice(0, 16), // stored, shown in the dashboard, used for lookup hash: sha256(key), // stored }; } export const sha256 = (s: string) => createHash("sha256").update(s).digest(); export function hashesMatch(a: Buffer, b: Buffer) { return a.length === b.length && timingSafeEqual(a, b); }

Store hashes, not keys

The table stores the prefix, the hash, the owning account, scopes and lifecycle timestamps:

CREATE TABLE api_keys ( id UUID PRIMARY KEY, account_id TEXT NOT NULL, prefix TEXT NOT NULL UNIQUE, key_hash BYTEA NOT NULL, scopes TEXT[] NOT NULL DEFAULT '{}', created_at TIMESTAMPTZ NOT NULL DEFAULT now(), last_used_at TIMESTAMPTZ, expires_at TIMESTAMPTZ, revoked_at TIMESTAMPTZ );

Password hashes need a slow function like Argon2, as the OWASP Password Storage Cheat Sheet recommends, because passwords are guessable. A 32-byte random key is not, so SHA-256 is enough and keeps the per-request check cheap. The OWASP REST Security Cheat Sheet also recommends treating API keys as one part of access control rather than the whole thing, which is what scopes are for.

Check the key on every request (Express)

import type { Request, Response, NextFunction } from "express"; import { Pool } from "pg"; import { sha256, hashesMatch } from "./keys"; const pool = new Pool(); export async function requireApiKey(req: Request, res: Response, next: NextFunction) { const key = req.header("authorization")?.replace(/^Bearer /, ""); if (!key?.startsWith("sk_live_")) return res.status(401).json({ error: "missing API key" }); const { rows } = await pool.query( `SELECT id, account_id, key_hash, scopes FROM api_keys WHERE prefix = $1 AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now())`, [key.slice(0, 16)], ); const row = rows[0]; if (!row || !hashesMatch(row.key_hash, sha256(key))) { return res.status(401).json({ error: "invalid API key" }); } pool.query("UPDATE api_keys SET last_used_at = now() WHERE id = $1", [row.id]).catch(() => {}); res.locals.account = { id: row.account_id, scopes: row.scopes as string[] }; next(); }

Return the same 401 for unknown and wrong keys so the response does not reveal which prefixes exist, and rate-limit failed attempts per IP and per prefix. Updating last_used_at on every request is a write per call; at high volume, batch it or only update when the stored value is older than a few minutes.

Rotation and revocation

Allow at least two active keys per account, and rotation is then create, deploy, revoke: the customer creates a new key, switches their integration, and revokes the old one, with last_used_at showing when the old key stopped being used. Revocation is setting revoked_at, which takes effect on the next request because the lookup filters on it. If you cache key lookups, keep the TTL short, or revocation is delayed by the cache.

API keys in Encore

Encore

Encore is a backend framework with built-in infrastructure for TypeScript and Go, and API key checks belong in its auth handler: one function that runs at the API gateway for any request carrying the auth parameters, before the endpoint is called. Endpoints opt in with auth: true and read the caller with getAuthData(), so no route can forget the middleware. encore run starts Postgres locally for the key table, and on deploy to your own AWS or GCP account Encore provisions RDS or Cloud SQL and provisions an IAM role for the service, or a service account on GCP.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

// auth/auth.ts import { APIError, Gateway, Header } from "encore.dev/api"; import { authHandler } from "encore.dev/auth"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { sha256, hashesMatch } from "./keys"; const db = new SQLDatabase("auth", { migrations: "./migrations" }); interface AuthParams { authorization: Header<"Authorization">; } interface AuthData { userID: string; // the owning account scopes: string[]; } export const auth = authHandler<AuthParams, AuthData>(async ({ authorization }) => { const key = authorization.replace(/^Bearer /, ""); if (!key.startsWith("sk_live_")) throw APIError.unauthenticated("invalid API key"); const row = await db.queryRow<{ account_id: string; key_hash: Buffer; scopes: string[] }>` SELECT account_id, key_hash, scopes FROM api_keys WHERE prefix = ${key.slice(0, 16)} AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now())`; if (!row || !hashesMatch(row.key_hash, sha256(key))) { throw APIError.unauthenticated("invalid API key"); } return { userID: row.account_id, scopes: row.scopes }; }); export const gateway = new Gateway({ authHandler: auth });
// reports/reports.ts import { api, APIError } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; export const list = api( { expose: true, auth: true, method: "GET", path: "/reports" }, async (): Promise<{ account: string }> => { const caller = getAuthData()!; if (!caller.scopes.includes("reports:read")) throw APIError.permissionDenied("missing scope"); return { account: caller.userID }; }, );

Throwing APIError.unauthenticated makes the gateway treat the request as unauthenticated, so auth: true endpoints reject it, while public endpoints still work. The handler shows up in every request trace in the local development dashboard, which makes a wrong prefix or an expired key easy to spot.

A coding agent adding a new endpoint only sets auth: true and checks a scope; it does not wire middleware or touch the key table.

Best fit: TypeScript or Go APIs that offer API keys to integrations and want the check enforced at the gateway for every endpoint, with the key table in their own AWS or GCP account.

Frequently asked questions

How should API keys be stored?

Store only a hash of the key, never the key itself, and show the full key to the customer once at creation. For long random keys a fast hash such as SHA-256 is enough, since there is nothing to brute-force; keep a short public prefix next to the hash so you can find the row and show customers which key is which.

How do I add API key authentication in Encore?

Define an authHandler that reads the Authorization header, hashes the presented key, looks it up in an Encore database and returns AuthData with the owning account and its scopes, or throws APIError.unauthenticated. Endpoints marked auth: true then only run for valid keys and read the caller with getAuthData().

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders