DEV Community

Jason Y. (dev_in_the_fog)
Jason Y. (dev_in_the_fog)

Posted on

Why One Regex Freezes Your Node.js Event Loop: Detecting Catastrophic Backtracking (ReDoS)

A single copy-pasted validation regex can pin a Node.js API server at 100% CPU with just one 35-byte request. Because JavaScript's V8 regex engine uses backtracking NFA execution, ambiguous quantifiers can explode into exponential work on non-matching input—a class of bug known as ReDoS (Regular Expression Denial of Service).

1. Why Valid Tests Pass While One Bad Input Freezes the Server

Consider this common email validation mistake:

// Vulnerable: nested quantifier ([a-zA-Z0-9._-]+)+
const badEmail = /^([a-zA-Z0-9._-]+)+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

// Matches instantly on valid input, stalls exponentially on missing '@'
badEmail.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!");
Enter fullscreen mode Exit fullscreen mode

On user@example.com, the engine succeeds on its first pass, so unit tests stay green. When the trailing @ is missing, V8 backtracks through every possible partition of the as—roughly 2^N steps—blocking the single-threaded event loop for all concurrent users.

2. Three Patterns Worth Flagging in Code Review

  1. Nested quantifiers: (a+)+, ([a-z0-9._-]+)+, (.*a){2,}
  2. Overlapping alternation inside repeated groups: (a|aa)+, (\w|\d)+
  3. Multiple unbounded wildcards in one expression: .*.*target

Flattening the group to a single linear character class (^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$) and enforcing a max input length check before invoking .test() eliminates the cliff.

3. Zero-Dependency CLI & Client-Side Visualizer

I put together a tiny MIT zero-dependency Node.js CLI (redos-lint) to catch these heuristics in CI, plus browser-only regex visualizers that keep your test strings strictly in local memory (0 bytes uploaded):

Top comments (1)

Collapse
 
parasraju profile image
Paras •

The passing tests hiding the freeze really stuck with me.