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.…