Next.js Middleware Builder
Generate production-ready middleware.ts for Next.js — auth protection, redirects, A/B testing, and matcher config explained.
Authentication Check
Protected Route Patterns
Requests matching these patterns require authentication.
Redirect Rules
A/B Testing
middleware.ts
Matcher Config Explanation
Frequently Asked Questions
What is Next.js middleware?▼
Next.js middleware runs before a request is processed, allowing you to modify the response, redirect users, rewrite URLs, or add headers — all at the Edge, before the page renders. It's defined in a middleware.ts file at the root of your project (or src/ directory). Middleware runs on every request that matches its config.matcher pattern.
What is the matcher config in Next.js middleware?▼
The matcher config in middleware.ts tells Next.js which paths to run middleware on. It supports regex-like patterns: '/((?!_next/static|_next/image|favicon.ico).*)' skips static assets. You can use arrays for multiple patterns. Matcher patterns must be static strings — no dynamic values or variables.
How do I protect routes with middleware?▼
Check authentication in middleware by reading a cookie (NextResponse.cookies.get), a header (request.headers.get), or a JWT in the Authorization header. If the user is not authenticated, call NextResponse.redirect() to send them to a login page. Always pass the request URL as the callbackUrl parameter so they return after login.
What is the difference between redirect and rewrite in middleware?▼
redirect changes the URL visible in the browser and sends a new request to the target path. rewrite proxies the request to a different path without changing the visible URL — the user sees the original URL but gets content from the rewrite target. Rewrites are useful for A/B testing, internationalization, and clean URL routing.
Can middleware access environment variables?▼
Yes, but with a caveat: middleware runs on the Edge Runtime, which is a restricted JavaScript environment. You can access process.env for server-side variables. However, you cannot use Node.js-specific APIs (fs, path, crypto built-ins). For JWT verification, use the Web Crypto API (crypto.subtle) or edge-compatible libraries like jose.
Related Products
on GumroadDevPlaybook Interview Vault
210+ real technical interview questions with model answers, asked at Google, Meta, Amazon, Microsoft, Stripe, and Shopify. Covers Frontend (55), Backend (55), System Design (50), and DSA (50). Available in English and Traditional Chinese.
Buy on Gumroad →TypeScript Quick Reference Toolkit
5 practical reference files for TypeScript developers: cheatsheet, TS vs JS comparison, 20 utility types with real examples, tsconfig best practices template, and 15 common mistakes guide. Print it. Keep it on your desk.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →You Might Also Need
TypeScript tsconfig.json Generator
Build a complete tsconfig.json visually. Choose a preset (Strict, Next.js, React, Node, Deno), toggle compiler options with explanations, enable path aliases, and copy the ready-to-use config.
Open free tool →
OAuth2 Flow Visualizer
Visualize OAuth2 authorization flows step by step. Compare Authorization Code, PKCE, Implicit, Client Credentials, and Device Code flows with JS code examples.
Open free tool →
SQL to TypeScript Types
Convert SQL CREATE TABLE statements to TypeScript interfaces and Zod schemas. Maps SQL column types to TypeScript with nullability.
Open free tool →
More Free Tools
Related Articles
Cloudflare Workers vs Vercel Edge Functions: 2026 Comparison
Deep comparison of Cloudflare Workers vs Vercel Edge Functions in 2026: runtime differences, limits, pricing, storage options, developer experience, and when to choose each.
Next.js 15 App Router Best Practices: Server Components, Caching & Performance
Master Next.js 15 App Router: when to use Server vs Client Components, how caching works in Next.js 15, data fetching patterns, Suspense boundaries, and performance optimization strategies.
Next.js 15 Server Actions: The Complete Guide for 2026
Master Next.js 15 Server Actions: form handling, progressive enhancement, caching, mutations, and real-world patterns. The definitive guide for 2026.
UploadThing: The Best File Upload Solution for Next.js in 2026
Complete guide to UploadThing covering setup with Next.js App Router, file type validation, image optimization, middleware auth, S3 alternatives comparison, and production patterns.
Hono.js: Build Blazing-Fast APIs for Edge and Serverless (2026 Guide)
Complete guide to Hono.js covering routing, middleware, RPC client, Cloudflare Workers, Bun, Deno, and Node.js runtimes, OpenAPI integration, and comparison with Express and Fastify for edge workloads.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →