ReDoS in Node.js and Next.js: Catastrophic Backtracking, Event Loop Stalls, and User-Supplied Patterns [2026]
ReDoS Is a Packet-Sized Outage
Most denial of service attacks need volume: a botnet, a flood of connections, something that costs the attacker money. ReDoS (Regular Expression Denial of Service) needs one HTTP request with a 40-character string. If that string reaches a vulnerable pattern — and the pattern is often written by your own team, years earlier, as a "simple validation" — the Node.js process stops serving anything. Not the one request: every request, on every route, because regex evaluation is synchronous JavaScript on the same single thread as your HTTP handler.
There is no await that saves you. AbortSignal does not reach inside RegExp.prototype.test. A timeout around the call does not fire until the call returns. Your health check times out, your orchestrator restarts the container, the attacker sends the same request again, and you have a crash loop with a five-line postmortem that says "the pod was unhealthy".
This is one of the few vulnerability classes where the fix is architectural rather than a patch: you decide who is allowed to express a pattern and where it is allowed to run.
How V8 Backtracks Into a 2^n Explosion
JavaScript regex engines (V8 included) are backtracking engines. For a pattern with alternation or nested quantifiers, the engine tries a path, fails, and rewinds to try the next one. That is fine when the number of paths is linear in the input length. It is catastrophic when the number of paths is exponential.
The canonical case:
// demo/redos.mjs — run with: node demo/redos.mjs
const evil = /^(a+)+$/;
for (const n of [16, 20, 22, 24, 26, 28]) {
const input = "a".repeat(n) + "!"; // one character that can never match
const t0 = process.hrtime.bigint();
evil.test(input);
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
console.log(`n=${n} -> ${ms.toFixed(2)} ms`);
}
Typical output on a modern laptop:
n=16 -> 0.35 ms
n=20 -> 4.10 ms
n=22 -> 15.80 ms
n=24 -> 62.40 ms
n=26 -> 249.10 ms
n=28 -> 998.70 ms
Every two extra characters multiply the work by four. At n=40 you are looking at hours. The (a+)+ construct is the tell: the outer + and the inner + can split the same run of a characters in exponentially many ways, and because the trailing ! guarantees overall failure, the engine must exhaust all of them before answering "no match".
Note what matters here: the failure is on non-matching input. Attackers do not need to satisfy your pattern, they only need to make the engine explore. That also means a WAF rule blocking obvious payloads does not help much — the haystack is just repeated letters.
The Five Shapes That Blow Up
| Shape | Example | Why it explodes |
|---|---|---|
| Nested quantifiers | ^(a+)+$ | Same characters can be partitioned exponentially many ways |
| Overlapping alternation | ^(a\|aa)+$ | Both branches consume a, so every position forks |
| Quantified group with an ambiguous tail | ^(\w+\s?)*$ | \s? lets the engine re-split word boundaries at every step |
| Adjacent unbounded wildcards | ^.*.*=.*$ | Each .* can absorb the rest, producing factorial-ish paths |
| Nested quantifier inside a lookaround | ^(?=(a+)+$) | Lookarounds still backtrack; the cost is hidden from the caller |
Two more that show up in real code and are easy to miss:
- Unanchored patterns over long input.
/(\w+\s?)+$/with no^forces the engine to retry the whole thing from every starting offset. - Case-insensitive Unicode classes.
/^\p{L}+$/iuover long strings with combining marks is far slower than people expect; the character-class expansion is large.
Real CVEs in this class include CVE-2024-27982 (undici header parsing), CVE-2022-36067 (the vm2 sandbox), CVE-2021-23341 in prismjs, and a long tail of semver, ansi-regex, trim, and nth-check advisories — all of them were reachable from a normal npm install and often from a plain string in a request body. Your dependency tree ships doom; your own code can ship it too.
Where an Attacker Actually Gets a Pattern
ReDoS payloads are trivial to send. The interesting question is why your application lets a string become a regex in the first place. The usual entry points:
- "Advanced search" with a regex toggle. Somebody shipped the power feature, nobody asked whether the tenant should have it.
- Saved filters and alert rules. A pattern stored in the database is compiled on every read — the injection point is the admin UI, the trigger is any later request that feeds it a long value.
- Tenant-configured validation. Custom field validation ("must match this format") in a multi-tenant product is an untrusted regex by definition.
- Routing, redaction, and routing tables. Webhook filters, log-scrubbing rules, URL rewrites: all pattern-driven, all editable by someone who is not a regex expert.
- LLM-generated code. A model that returns
new RegExp(userInput)because the prompt said "make it flexible" — and it compiles. - Query parameters passed straight to
RegExp. The classic:
// app/api/search/route.ts — VULNERABLE, do not ship
import { NextRequest, NextResponse } from "next/server";
const cache = new Map<string, RegExp>();
export async function GET(req: NextRequest) {
const pattern = req.nextUrl.searchParams.get("pattern") ?? "";
if (!cache.has(pattern)) cache.set(pattern, new RegExp(pattern, "i"));
const rx = cache.get(pattern)!;
const rows = await db.product.findMany({ select: { id: true, name: true } });
return NextResponse.json(rows.filter((row) => rx.test(row.name)));
}
This has two bugs wearing one coat. The first is ReDoS: ?pattern=%5E(a%2B)%2B%24 is a valid pattern, and every one of your product names becomes a potential exponential probe. The second is an unbounded cache keyed by attacker-controlled strings — a slow memory leak that ends in an OOM restart. A third, subtler one: rows are fetched in full and filtered in memory, so the dangerous work happens after you have already paid for the database round trip.
Confirm it with timing, not with intuition:
# 30 a's + "!" against a product name of the same shape
time curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" \
"http://localhost:3000/api/search?pattern=%5E(a%2B)%2B%24"
If the response time climbs with the length of the stored name, you have it. If you want to prove it in a unit test without hanging CI, run the pattern in a worker with a hard budget.
Detect It Before Production Does
Instrumentation first — you cannot fix what you cannot see. Event loop lag is the signal that a synchronous regex is eating the process:
// instrumentation.mjs — import once at boot (or from instrumentation.ts in Next.js)
import { monitorEventLoopDelay } from "node:perf_hooks";
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();
setInterval(() => {
const p99 = histogram.percentile(99) / 1e6;
const max = histogram.max / 1e6;
if (p99 > 100) {
console.warn(`event_loop_lag p99=${p99.toFixed(1)}ms max=${max.toFixed(1)}ms`);
}
histogram.reset();
}, 5_000).unref();
Second, a probe that fails a pattern which cannot finish in a fixed budget. This is the only way to test an untrusted pattern safely, because the worker can be terminated:
// scripts/regex-budget.mjs — compile a pattern under a hard time budget
import { Worker } from "node:worker_threads";
const PROBE = `
const { parentPort, workerData } = require("node:worker_threads");
const rx = new RegExp(workerData.pattern, workerData.flags);
const t0 = process.hrtime.bigint();
const ok = rx.test(workerData.haystack);
parentPort.postMessage({ ok, ms: Number(process.hrtime.bigint() - t0) / 1e6 });
`;
export function probePattern(pattern, flags = "", budgetMs = 50) {
return new Promise((resolve) => {
// adversarial haystack: repeated chars + a guaranteed mismatch at the end
const haystack = "a".repeat(64) + "!";
const worker = new Worker(PROBE, { eval: true, workerData: { pattern, flags, haystack } });
const timer = setTimeout(() => {
worker.terminate();
resolve({ ok: false, timedOut: true, budgetMs });
}, budgetMs);
worker.once("message", (result) => {
clearTimeout(timer);
worker.terminate();
resolve({ ...result, timedOut: false });
});
worker.once("error", (error) => {
clearTimeout(timer);
resolve({ ok: false, error: error.message });
});
});
}
Run it in a unit test over every pattern your users can store. { ok: false, timedOut: true } is a rejected pattern, not a slow one — and worker.terminate() is the only cancellation primitive you actually have.
Layer 1: Delete the Pattern Language
The best ReDoS fix is not a safer engine, it is not accepting regex. Most "advanced search" needs four operations. Enumerate them and the vulnerability class disappears:
// lib/filters.ts — the whole filter language, no regex anywhere
export type Filter =
| { kind: "contains"; value: string }
| { kind: "startsWith"; value: string }
| { kind: "equals"; value: string }
| { kind: "oneOf"; values: string[] };
const MAX_VALUE = 120;
export function parseFilter(input: unknown): Filter {
// validate shape with zod/valibot in real code, then:
const f = input as Filter;
if (f.kind === "oneOf") {
if (f.values.length > 20) throw new Error("too many values");
return { kind: "oneOf", values: f.values.map((v) => v.slice(0, MAX_VALUE)) };
}
return { kind: f.kind, value: f.value.slice(0, MAX_VALUE) };
}
If you must express it in SQL, escape the LIKE metacharacters so a user-supplied % does not turn a prefix filter into a table scan:
// Escape LIKE wildcards before interpolation into a parameterized query
const escaped = value.replace(/[\\%_]/g, (ch) => `\\${ch}`);
await db.$queryRaw`SELECT id, name FROM "Product" WHERE name ILIKE ${escaped + "%"}`;
That replace is itself a regex — a safe one, fixed, bounded, and written by you. That is the distinction that matters throughout this article: patterns in source code are auditable; patterns from users are not.
Layer 2: RE2 for Patterns You Genuinely Need
Sometimes users really do need expressions: log parsers, redaction rules, data pipelines. In that case, swap the engine. RE2 is a linear-time engine — it gives up backreferences and lookarounds, which is exactly the trade you want, because those features are where super-linear backtracking comes from.
npm install re2
// lib/untrusted-regex.ts — untrusted pattern, linear-time engine
import RE2 from "re2";
const MAX_PATTERN = 200;
export function compileUntrusted(pattern: string, flags = "i"): RE2 {
if (pattern.length > MAX_PATTERN) {
throw new Error("pattern exceeds length limit");
}
try {
// RE2 throws on backreferences and lookarounds — that is the point
return new RE2(pattern, flags);
} catch {
throw new Error("pattern uses unsupported constructs");
}
}
Two caveats worth knowing before you ship it:
re2is a native addon. It has prebuilt binaries for common platforms, but Alpine/musl, ARM, and unusual Node versions may trigger a source build. Test your deploy image, and keep a fallback path ifrequire("re2")fails.- Rejecting backreferences and lookarounds will change behaviour for tenants who leaned on them. That is a product decision, not a bug — surface a clear validation error instead of silently returning wrong matches.
Node also ships an experimental linear engine in V8. It is useful as a safety net rather than a primary defense:
# Fall back to the non-backtracking engine after N backtracks (V8 flags, experimental)
node --enable-experimental-regexp-engine-on-excessive-backtracks \
--regexp-backtrack-limit=1000 server.js
The flags are experimental and their names have changed between V8 versions, so pin them in your Dockerfile with a comment and verify the behaviour in a test that would otherwise hang.
Layer 3: Bound Everything, Then Lint
Even with RE2, hard limits make the blast radius predictable:
// Bound the haystack, not just the pattern
const MAX_HAYSTACK = 4_096;
export function safeTest(rx: RE2, value: string): boolean {
const haystack = value.length > MAX_HAYSTACK ? value.slice(0, MAX_HAYSTACK) : value;
return rx.test(haystack);
}
And lint the patterns you wrote yourself, because your own code is the most common source:
// eslint.config.mjs — catch super-linear backtracking at review time
import regexp from "eslint-plugin-regexp";
export default [
regexp.configs["flat/recommended"],
{
rules: {
"regexp/no-super-linear-backtracking": "error",
"regexp/no-useless-quantifier": "warn",
"regexp/prefer-lookaround": "off",
},
},
];
For patterns already stored in the database (saved filters, alert rules, tenant validation), audit them offline with a ReDoS checker instead of guessing:
# recheck reports ambiguity and exponential worst cases
npx recheck '^(\w+\s?)*$'
# or scan a JSON export of stored patterns, one per line
jq -r '.patterns[]' exports/tenant-patterns.json | while read -r p; do
npx recheck --json "$p" | jq -r '.source + " -> " + (.complexity | tostring)'
done
Layer 4: Rate Limit and Isolate What Slips Through
No layer above is perfect, so assume one pattern survives. Give the damage a ceiling:
- Per-tenant rate limit on pattern submission and pattern execution. A tenant that runs 2,000 saved filters per minute is either broken or hostile; both deserve a 429.
- Run untrusted evaluation in a dedicated worker pool with
resourceLimits, and terminate on budget. Keep it off the main HTTP thread so a single runaway pattern does not stop health checks. - Cap concurrent evaluations per process. Twenty workers burning CPU is the same outage with a nicer architecture diagram.
- Alert on event loop p99 and on
max. A single spike is a signal; ignore it and the next one arrives as a restart. - Log the pattern and the tenant on every timeout. You need to know which stored rule is the bomb before the next request finds it.
The Startup Checklist
- [ ] No route passes
req.query, a request body field, or a database value intonew RegExp(...). - [ ] "Advanced search" exposes enumerated filters (contains, startsWith, equals, oneOf), not a pattern box.
- [ ] If patterns are a real requirement, they are compiled with RE2, never with the V8 backtracking engine.
- [ ] Pattern length is capped (200 chars or less) and the haystack is capped (4,096 chars or less) before any test.
- [ ] Every untrusted pattern is executed inside a worker with a hard time budget and
terminate()on overrun. - [ ]
eslint-plugin-regexpwithregexp/no-super-linear-backtrackingis enabled in CI, and the build fails on violations. - [ ] Stored patterns (filters, alert rules, tenant validators) were audited offline with
recheckorredos-detector. - [ ] Any regex cache is bounded and keyed by a hash, not by an unbounded attacker string.
- [ ] Rate limits exist on pattern submission and on pattern execution, per tenant.
- [ ] Event loop lag (p99 and max) is exported to your metrics backend with an alert attached.
- [ ] A unit test asserts that a known-evil pattern is rejected or times out, so a future refactor cannot quietly remove the guard.
- [ ] Node/V8 flags and native addons (
re2) are pinned and verified in the exact image you deploy.
What to Do This Week
Grep first: grep -rn "new RegExp(" src/ app/ pages/ lib/ and grep -rn "\.test(" src/ | grep -v "test(" will show you most of the attack surface in ten minutes. Triage every hit into "fixed pattern written by us" (lint it) or "pattern from outside" (RE2, or delete the feature). Then take the ten most expensive stored patterns from production and run them through recheck — you will usually find at least one that a customer created by accident. Finally, wire the worker-budget probe into your test suite for every endpoint that accepts a filter. ReDoS is not stopped by intent; it is stopped by the fact that the code physically cannot run a pattern without a deadline.
Want your API's filter endpoints, stored patterns, and event-loop headroom reviewed by someone who attacks them for a living? Schedule a security audit and we will try to hang your process with a string, then show you exactly which line let it happen.
Next week: presigned URL security for S3-compatible object storage — scope, expiry, content-type confinement, and the confused-deputy bug that turns a safe bucket into a public one.
JS Security Audit
Audits led by a senior JavaScript security engineer with 10+ years of experience.