# Next.js Edge Firewall

Sub-1 ms request firewall for Next.js apps running on Netlify Edge,
Vercel Edge, or Cloudflare Workers. Blocks scanners, attack paths,
and injection attempts in middleware *before* the request reaches
your serverless function.

**MIT License · Production-tested at coreindustry.de · No dependencies.**

---

## What it blocks

| Layer | Threat | Detection |
|-------|--------|-----------|
| 1 | Bad-bot / scanner User-Agents | Regex against 25+ known patterns (`sqlmap`, `nikto`, `nmap`, `metasploit`, `dirbuster`, …) |
| 2 | Known attack paths | Regex against `/.env`, `/wp-admin`, `/phpMyAdmin`, `/.git`, `/etc/passwd`, etc. |
| 3 | SQL/XSS/template-injection in query strings | 5 dedicated regexes, URL-decoded once |
| 4 | Path-traversal in URL path | Same injection regex re-applied to `pathname` |
| 5 | Per-IP rate limit | In-memory sliding window, FNV-1a hashed IP |

Returns `403 Forbidden` for layers 1–3, `429 Too Many Requests` for layer 4.

## Latency

Measured on Netlify Edge Functions (Frankfurt POP), 1000-request sample:
- p50: **0.8 ms**
- p95: **1.4 ms**
- p99: **2.1 ms**

Sub-1 ms because: pure regex, no async I/O, no external state, FNV-1a is
single-pass.

## Why we built this

We needed WAF-style protection for our B2B SaaS clients but didn't want
to add Cloudflare ($240/mo per zone) or AWS WAF ($5 + $1/rule/mo)
when 95% of attacks we see are crawler-pattern based. Edge middleware
runs free on Netlify/Vercel anyway.

After 3 months in production at coreindustry.de we've blocked ~12 k
scanner hits per month with zero false positives on real users.

## Install

Drop these files into your Next.js 15+ project:

```
middleware.ts          # 130 LOC — wires the layers
lib/firewall-edge.ts   # 90 LOC — the regex sets + rate limit
```

Both files are below as a single self-contained snippet. Copy, paste,
adjust your matcher pattern if you have routes that should be excluded.

## Compatibility

- Next.js 15+ App Router (`middleware.ts` API)
- Edge runtimes: Netlify Edge ✓ · Vercel Edge ✓ · Cloudflare Workers ✓
- Node.js runtime: also works (slower, but functional)
- No npm dependencies — pure web-standard APIs only

## What it does NOT do

- **No DDoS protection** — for that use Cloudflare's free tier in front
- **No JS challenge / CAPTCHA** — out of scope for middleware
- **No managed rule updates** — you maintain the regex lists yourself
- **No persistent rate-limit storage** — in-memory only, resets per
  worker restart (acceptable for our use case; if you need persistent,
  swap the `RATE_MAP` for Upstash/Redis)

## Built by

[Core Industry](https://coreindustry.de) — Festpreis-Software-Agentur,
Bottrop NRW. We use this in production for B2B-SaaS-Plattformen.

If this snippet saves you a Cloudflare subscription, consider giving us
a shoutout on Hacker News or LinkedIn.

## License

MIT — do whatever you want with this code, attribution appreciated but
not required.
