DEV Community

Cover image for Stop Catastrophic Regex Backtracking (ReDoS) in JavaScript: 5 Patterns That Freeze Node.js & How to Fix Them
Omni Tools
Omni Tools

Posted on

Stop Catastrophic Regex Backtracking (ReDoS) in JavaScript: 5 Patterns That Freeze Node.js & How to Fix Them

A single innocent-looking validation regex like /^([a-zA-Z0-9._-]+)+@[a-zA-Z0-9.-]+$/ can take down an entire Node.js API server with a 35-byte request body.

Because JavaScript's built-in RegExp engine (V8 Irregexp) uses a backtracking NFA, certain patterns take O(2^n) exponential time on failing inputs. In a single-threaded Node.js event loop, one malicious input blocks every other HTTP request on that worker - an attack known as ReDoS (Regular Expression Denial of Service).

Here are the 5 most common ReDoS patterns developers accidentally ship to production, and the exact linear-time O(n) replacements.


5 Vulnerable Patterns vs. Safe O(n) Fixes

Use Case Vulnerable Regex (ReDoS!) Safe Linear-Time Replacement
1. Username / Slug /^([a-z0-9]+)+$/ /^[a-z0-9]{1,64}$/
2. Trimming Whitespace `/^\s+ \s+$/g or /\s+$/ with .*\s+$`
3. Email Validation /^(\w+\.?)+@([\w-]+\.)+[a-z]{2,}$/ /^[\w.%+-]{1,64}@[\w.-]{1,253}\.[a-z]{2,}$/i
4. HTML Tag Stripping /<([a-z]+)([^<]+)*(?:>(.*)<\/\1>)/ /<[^>]{1,500}>/g (or a real HTML parser)
5. Overlapping Alternation `/^(\w+ \w+\d+)+$/`

Notice what every single dangerous pattern has in common: nested quantifiers ((...+)+, (...*)*) or overlapping alternatives ((a|aa)+) followed by a mismatch at the end of the string.


Reproducing the Freeze Locally (Safe 24-Char Demo)

You can measure exponential growth safely in Node.js without locking your machine by keeping n between 18 and 24:

const vulnerable = /^([a-z0-9]+)+$/;
const safe = /^[a-z0-9]{1,64}$/;

for (const n of [18, 20, 22, 24]) {
  // Trailing "!" forces the regex engine to fail and try every partition
  const evilInput = "a".repeat(n) + "!";

  const t0 = performance.now();
  vulnerable.test(evilInput);
  const badMs = (performance.now() - t0).toFixed(2);

  const t1 = performance.now();
  safe.test(evilInput);
  const goodMs = (performance.now() - t1).toFixed(4);

  console.log(`n=${n} | vulnerable: ${badMs}ms | safe: ${goodMs}ms`);
}
Enter fullscreen mode Exit fullscreen mode

Watch the vulnerable column double with every single extra character (n=20 -> 22 -> 24). By n=35, that one test() call hangs the entire Node.js process for minutes. Meanwhile, safe stays flat at < 0.01ms.


4 Golden Rules to Keep Every JS Regex ReDoS-Proof

1. Cap Input Length Before Running RegExp

Always check input.length <= MAX_LEN before calling .test() or .match() on untrusted user data (emails max out at 254 chars per RFC 5321, URLs at 2048 chars).

export function isValidEmail(raw: string): boolean {
  if (raw.length === 0 || raw.length > 254) return false;
  return /^[^\s@]{1,64}@[^\s@]{1,253}\.[^\s@]{2,}$/.test(raw);
}
Enter fullscreen mode Exit fullscreen mode

2. Replace .* and .+ With Negated Character Classes

Greedy wildcards like "(.+)" backtrack across the entire line when a closing quote is missing. Negated character classes like "([^"]+)" never backtrack past the delimiter:

// Risky on long strings with multiple quotes:
const slow = /"(.+)"/;

// Fast, linear-time, stops at the first closing quote:
const fast = /"(?<value>[^"\r\n]{0,500})"/;
Enter fullscreen mode Exit fullscreen mode

3. Never Nest Quantifiers Across the Same Character Set

Whenever you see + or * inside a group that itself has + or * (like ([a-z]+_?)+), flatten it into a single repetition with an explicit separator:

// Safe snake_case identifier (linear time):
const snakeCase = /^[a-z0-9]+(?:_[a-z0-9]+)*$/;
Enter fullscreen mode Exit fullscreen mode

Because the underscore _ is mandatory between every repeat, the engine has only one deterministic path through the string - zero ambiguity, zero catastrophic backtracking.

4. Use Named Capture Groups for Readability

Instead of brittle match[1] / match[2] indexes, ES2018+ named groups make complex expressions self-documenting:

const logLine = /^(?<level>INFO|WARN|ERROR)\s+\[(?<ts>[^\]]+)\]\s+(?<msg>.{1,300})$/;
const parsed = logLine.exec("ERROR [2026-11-30T10:00Z] Timeout connecting to DB")?.groups;
// { level: "ERROR", ts: "2026-11-30T10:00Z", msg: "Timeout connecting to DB" }
Enter fullscreen mode Exit fullscreen mode

Debug & Visualize Capture Groups Live

Before pushing a new validation pattern to production, it helps to inspect every match and capture group visually against edge-case inputs (empty strings, trailing symbols, and long payloads). You can test patterns privately inside your browser using the free Regex Visualizer & Tester on OmniTools (runs 100% client-side with zero uploads and built-in email/URL/phone presets). And if you are also scheduling cleanup jobs or log rotators, check out our Cron Expression Generator & Explainer.

Have you ever caught a ReDoS freeze in production logs or a security audit? Share the regex that bit you in the comments!

Top comments (0)