const rawOrigins = process.env.ALLOWED_ORIGINS ?? "";
export const allowedOrigins = new Set(
rawOrigins
.split(",")
.map((o) => o.trim())
.filter(Boolean)
);
export const allowedMethods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
export const allowedHeaders = ["Content-Type", "Authorization", "X-Requested-With"];
export const preflightMaxAgeSeconds = 600;
export function isOriginAllowed(origin: string | undefined): boolean {
// No Origin header => same-origin or non-browser client; not subject to CORS.
if (!origin) return true;
return allowedOrigins.has(origin);
}
import { Request, Response, NextFunction } from "express";
import {
isOriginAllowed,
allowedMethods,
allowedHeaders,
preflightMaxAgeSeconds,
} from "./corsConfig";
export function corsMiddleware(req: Request, res: Response, next: NextFunction) {
const origin = req.headers.origin;
res.setHeader("Vary", "Origin");
if (origin && isOriginAllowed(origin)) {
// Echo the exact vetted origin, never "*".
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
if (req.method === "OPTIONS") {
if (!origin || !isOriginAllowed(origin)) {
res.status(403).end();
return;
}
res.setHeader("Access-Control-Allow-Methods", allowedMethods.join(", "));
res.setHeader("Access-Control-Allow-Headers", allowedHeaders.join(", "));
res.setHeader("Access-Control-Max-Age", String(preflightMaxAgeSeconds));
res.status(204).end();
return;
}
next();
}
import express, { Request, Response } from "express";
import cookieParser from "cookie-parser";
import { corsMiddleware } from "./corsMiddleware";
const app = express();
app.use(corsMiddleware);
app.use(express.json());
app.use(cookieParser());
app.get("/api/profile", (req: Request, res: Response) => {
const session = req.cookies?.session;
if (!session) {
res.status(401).json({ error: "unauthenticated" });
return;
}
res.json({ id: session, name: "Ada Lovelace" });
});
app.post("/api/events", (req: Request, res: Response) => {
res.status(201).json({ received: req.body });
});
const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => {
console.log(`listening on :${port}`);
});
The wildcard Access-Control-Allow-Origin: * is the easy default, but it cannot be combined with credentialed requests and it grants every site on the internet access to an API's browser-facing responses. These files show an explicit, allowlist-driven CORS setup where the server echoes back only origins it has vetted, which is the approach required whenever cookies or Authorization headers cross origins.
In corsConfig.ts, the allowed origins live in a Set for O(1) membership checks, seeded from an environment variable so staging and production differ without code changes. The exported isOriginAllowed function centralizes the decision and deliberately treats a missing Origin header (same-origin or server-to-server calls, which browsers never restrict) as allowed, while rejecting anything not explicitly listed. Keeping this logic pure makes it trivial to unit test and reuse.
The corsMiddleware.ts tab implements the protocol by hand rather than trusting a black box. It reads the request Origin, and only when isOriginAllowed returns true does it set Access-Control-Allow-Origin to that exact value — never *. Because the header now varies per request, it also sets Vary: Origin so shared caches do not serve one origin's permissive response to another. Access-Control-Allow-Credentials is emitted only for known origins, since sending it alongside a wildcard is an error browsers reject outright.
Preflight OPTIONS requests are answered directly with 204, advertising the permitted methods and headers and an Access-Control-Max-Age so browsers can skip repeated preflights for ten minutes. Disallowed origins simply receive no CORS headers, causing the browser to block the response — the server never throws, it just stays silent.
The app.ts tab wires the middleware ahead of the routes and demonstrates a credentialed endpoint. The trade-off of this pattern is maintenance: every new frontend origin must be added to the allowlist, and forgetting Vary: Origin behind a CDN is a classic cache-poisoning pitfall. In exchange the API gains a precise, auditable boundary that safely supports cookies and tokens, which the wildcard approach can never do.
Related snips
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
#!/usr/bin/env bash
set -euo pipefail
export VAULT_ADDR="https://vault.internal:8200"
export VAULT_TOKEN="${VAULT_TOKEN:?missing VAULT_TOKEN}"
Secrets management with environment isolation and Vault
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";
const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";
JWT access + refresh token rotation (conceptual)
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
package deps
import (
"net"
"net/http"
"time"
HTTP client tuned for production: timeouts, transport, and connection reuse
Share this code
Here's the card — post it anywhere.