Course contentsShow
← JavaScript
Lesson 1740 of 2,72336. Regular ExpressionsFree lesson

ReDoS and Security

Regex Denial of Service attacks exploit backtracking; never use user input in complex patterns.

ReDoS and Security

You'll learn how malicious input can turn innocent regex patterns into performance nightmares and what to do about it.


What Is ReDoS?

ReDoS (Regular Expression Denial of Service) is an attack that exploits how regex engines handle backtracking. When a poorly designed pattern encounters specially crafted input, the engine tries exponentially more combinations, causing your application to freeze or crash.

Remember catastrophic backtracking from the previous lesson? Attackers intentionally trigger it by feeding user input into vulnerable patterns.


The Core Security Risk

Consider this pattern:

const pattern = /^(a+)+$/;

If a user submits "aaaaaaaaaaaaaaaaaaaaaaaaaaX" (many a's followed by something that doesn't match), the engine tries countless combinations before giving up. With just 20–30 characters, evaluation can take seconds or minutes.

The golden rule: Never trust user input in complex regex patterns, especially those with:

  • Nested quantifiers like (a+)+ or (a*)*
  • Alternations with overlapping matches
  • Unbounded repetition on broad character classes

Protecting Your Application

  1. Validate input length before applying regex
  2. Use simpler patterns when possible (string methods often suffice)
  3. Timeout regex execution in critical paths (though JavaScript doesn't have built-in timeouts)
  4. Test patterns with long, worst-case strings
  5. Avoid user-controlled patterns — never pass raw user input to new RegExp()

Example of Safe Practice

// Unsafe: user input + complex pattern
const userInput = req.body.search;
const unsafePattern = new RegExp(`(${userInput})+`);

// Safer: validate length, use fixed pattern
if (userInput.length > 100) throw new Error("Too long");
const safePattern = /^[a-z]{1,50}$/; // Fixed, bounded

Key Takeaway: Regex backtracking can be weaponized—always sanitize input, limit pattern complexity, and never let users control your regex logic.