CSRF Double-Submit Token
Issue HMAC-bound CSRF tokens and verify that the header, cookie and session agree before accepting a state change.
Code
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
export interface CsrfCheckInput {
headerToken?: string;
cookieToken?: string;
sessionId: string;
}
export function createCsrfToken(sessionId: string, secret: string): string {
if (!sessionId || !secret) throw new TypeError("sessionId and secret are required");
const nonce = randomBytes(18).toString("base64url");
const signature = createHmac("sha256", secret)
.update(sessionId + "." + nonce)
.digest("base64url");
return nonce + "." + signature;
}
export function verifyCsrfToken(input: CsrfCheckInput, secret: string): boolean {
const { headerToken, cookieToken, sessionId } = input;
if (!headerToken || !cookieToken || !sessionId) return false;
const header = Buffer.from(headerToken);
const cookie = Buffer.from(cookieToken);
if (header.length !== cookie.length || !timingSafeEqual(header, cookie)) return false;
const separator = headerToken.lastIndexOf(".");
if (separator <= 0) return false;
const nonce = headerToken.slice(0, separator);
const signature = headerToken.slice(separator + 1);
const expected = createHmac("sha256", secret)
.update(sessionId + "." + nonce)
.digest("base64url");
const provided = Buffer.from(signature);
const expectedBuffer = Buffer.from(expected);
return provided.length === expectedBuffer.length
&& timingSafeEqual(provided, expectedBuffer);
}
export function csrfCookie(token: string, secure = true): string {
const flags = ["Path=/", "SameSite=Lax", secure ? "Secure" : ""].filter(Boolean);
return "csrf_token=" + encodeURIComponent(token) + "; " + flags.join("; ");
}How it works
Count the functions createCsrfToken, verifyCsrfToken and csrfCookie as the entire surface area of CSRF Double-Submit Token.
The only import source is node:crypto, a Node.js built-in, exposing createHmac, randomBytes, timingSafeEqual. When the guard condition holds, TypeError is thrown rather than a bogus value returned.
Points of care
- The only import,
node:crypto, is part of the Node.js standard library. cryptoexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
!sessionId || !secretshort-circuits the flow with an earlythrowwhen its condition holds.
Using it
The primary signature is export function createCsrfToken(sessionId: string, secret: string)
Import createCsrfToken from the file and call it — the rest of the code is implementation detail.
Key statements
if (header.length !== cookie.length || !timingSafeEqual(header, cookie)) return false;
if (!sessionId || !secret) throw new TypeError("sessionId and secret are required");
return "csrf_token=" + encodeURIComponent(token) + "; " + flags.join("; ");
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- How does the code behave when input is bad?
- `TypeError` is raised at the guard (`!sessionId || !secret`), so invalid state never reaches the main logic.
- Are there third-party dependencies?
- No. The imports resolve to Node.js core modules, which the runtime provides.
Report a problem with this exampleOpens a pre-filled issue on GitHub.