REGEXVAULTv2.0
Security/API Keys & Tokens
Verified Safe

JWT Header (Decoded Algorithm Field) Regex for JavaScript

/^\{"alg":"(HS256|HS384|HS512|RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512|EdDSA)","typ":"JWT"(?:,"kid":"[^"]{1,100}")?\}$/

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching jwt header (decoded algorithm field), ported and verified for JavaScript. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your JavaScript project — whether you're validating in an Express middleware, a Next.js API route, or a client-side form.

Javascript Implementation

Javascript
// JWT Header (Decoded Algorithm Field)
// ReDoS-safe | RegexVault — Security > API Keys & Tokens

const jwtHeaderDecodedAlgorithmFieldRegex = /^\{"alg":"(HS256|HS384|HS512|RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512|EdDSA)","typ":"JWT"(?:,"kid":"[^"]{1,100}")?\}$/;

function validateJwtHeaderDecodedAlgorithmField(input: string): boolean {
  return jwtHeaderDecodedAlgorithmFieldRegex.test(input);
}

// Example
console.log(validateJwtHeaderDecodedAlgorithmField("{"alg":"HS256","typ":"JWT"}")); // true

Test Cases

Matches (Valid)
Rejects (Invalid)
{"alg":"HS256","typ":"JWT"}{"alg":"none","typ":"JWT"}
{"alg":"RS256","typ":"JWT","kid":"key-id-12345"}{"alg":"HS256"}
{"alg":"ES256","typ":"JWT"}{"alg":"RS256","typ":"jwt"}
{"typ":"JWT","alg":"RS256"}

When to use this pattern

This pattern is drawn from the Security > API Keys & Tokens category and carries a ReDoS-safe certification. That matters for JavaScript developers because especially critical in long-running Node.js event loops where a ReDoS vulnerability can block the entire process. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

The algorithm confusion attack (CVE class) occurs when the verifier is tricked into using a different algorithm than intended. Always specify and enforce the expected algorithm in your verification code — never trust the algorithm from the token header.

Technical Notes

Explicitly excludes 'none' and weak algorithms (HS1, MD5). Approved algorithms: HMAC-SHA (HS256/384/512), RSA PKCS#1 v1.5 (RS*), ECDSA (ES*), RSA-PSS (PS*), EdDSA. The 'kid' (key ID) claim is optional. JSON key order is enforced — real parsers should be order-agnostic.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern