Next.js Middleware Not Working— Fixed [Complete Guide 2026]
Also covers: file location · matcher config · Edge Runtime · auth redirects · infinite redirect loops
⚡ The Symptom
// Middleware silently does nothing — no redirect, no log
// OR:
Error: Middleware is not supported with the "nodejs" runtime.
// OR:
// Infinite redirect loop on protected routes✅ Correct middleware.ts location & structure
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
export function middleware(request: NextRequest) {
// Your logic here
return NextResponse.next() // ← always return something
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
}Why Next.js Middleware Silently Does Nothing
Next.js middleware is powerful but has strict requirements. The most common reason it silently does nothing is the file being in the wrong location. The second most common reason is a matcher config that accidentally excludes all routes. Both cause middleware to be completely ignored with no error message.
Check middleware.ts File Location
Most common cause — wrong directorymy-nextjs-app/
├── middleware.ts ← ✅ CORRECT — project root
├── next.config.ts
├── package.json
├── app/
│ ├── layout.tsx
│ └── page.tsx
└── ...
# ❌ WRONG locations:
app/middleware.ts ← inside app/ — will not run
src/middleware.ts ← inside src/ — only works if using src/ layout
pages/middleware.ts ← inside pages/ — will not runIf you use a src/ directory layout (src/app/ instead of app/), place middleware at src/middleware.ts — not at the project root.
Fix the Matcher Configuration
Middleware runs but not on expected routesThe matcher in the exported config controls which routes trigger the middleware. An overly restrictive matcher silently skips routes.
export const config = {
// ✅ Run on all routes
matcher: ["/(.*)" ],
// ✅ Run on all routes EXCEPT static files and API routes
matcher: ["/((?!_next/static|_next/image|favicon.ico|api/).*)"],
// ✅ Run only on /dashboard and everything under it
matcher: ["/dashboard/:path*"],
// ✅ Multiple protected sections
matcher: ["/dashboard/:path*", "/admin/:path*", "/account/:path*"],
// ❌ Missing leading slash — won't match
matcher: ["dashboard/:path*"],
}Always Return a Response
Middleware that returns undefined causes errorsEvery code path in your middleware must return a NextResponse. If the function returns undefined (e.g., a missing else branch), Next.js will throw an error.
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// ✅ Always return — every branch covered
if (pathname.startsWith("/admin")) {
const token = request.cookies.get("admin_token")?.value
if (!token) {
return NextResponse.redirect(new URL("/login", request.url))
}
}
return NextResponse.next() // ← fallthrough — always return this
}Fix Auth Redirects and Infinite Loops
Protected routes redirecting to login and backAn infinite redirect loop happens when the login page itself matches the middleware matcher and triggers another redirect. Always exclude the login page from the protected matcher.
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
const PROTECTED_PATHS = ["/dashboard", "/account", "/admin"]
const PUBLIC_PATHS = ["/login", "/register", "/api/auth"]
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const token = request.cookies.get("auth_token")?.value
const isProtected = PROTECTED_PATHS.some(p => pathname.startsWith(p))
const isPublic = PUBLIC_PATHS.some(p => pathname.startsWith(p))
// Redirect unauthenticated users away from protected routes
if (isProtected && !token) {
const loginUrl = new URL("/login", request.url)
loginUrl.searchParams.set("redirect", pathname) // preserve destination
return NextResponse.redirect(loginUrl)
}
// Redirect authenticated users away from login page
if (isPublic && token) {
return NextResponse.redirect(new URL("/dashboard", request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
}Fix Edge Runtime Limitations
Node.js APIs crashing middlewareMiddleware runs in the Edge Runtime — not Node.js. You cannot use fs, path, crypto, jsonwebtoken, or any Node.js-specific library. Use Web API alternatives instead.
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
// ❌ jsonwebtoken uses Node.js crypto — not Edge compatible
// import jwt from "jsonwebtoken"
// ✅ Use jose — Edge-compatible JWT library
import { jwtVerify } from "jose"
const SECRET = new TextEncoder().encode(process.env.JWT_SECRET!)
export async function middleware(request: NextRequest) {
const token = request.cookies.get("auth_token")?.value
if (!token) {
return NextResponse.redirect(new URL("/login", request.url))
}
try {
await jwtVerify(token, SECRET)
return NextResponse.next()
} catch {
return NextResponse.redirect(new URL("/login", request.url))
}
}Edge-compatible libraries: jose (JWT), bcryptjs (avoid — too slow on Edge), @supabase/ssr (auth). Incompatible: jsonwebtoken, bcrypt, mongoose, prisma, fs, path.
Prevention
- Place middleware.ts at the project root (or src/ root if using src/ layout) — never inside /app or /pages
- Always export a config with an explicit matcher — never rely on the default behaviour
- Exclude static assets from the matcher: _next/static, _next/image, favicon.ico
- Every code path must return a NextResponse — add NextResponse.next() as the final fallthrough
- Exclude the login/public pages from protected matchers to prevent infinite redirect loops
- Use Edge-compatible libraries only — jose for JWT, Web Crypto API for hashing
Frequently Asked Questions
Where should middleware.ts be placed in Next.js?+−
Why is my Next.js middleware not running on any routes?+−
How do I make middleware run on all routes?+−
Can I use Node.js APIs in Next.js middleware?+−
Why does my middleware redirect loop infinitely?+−
Can Next.js middleware read request body?+−
Need Expert Help?
We Build Secure Next.js Applications
Softplix engineers build production Next.js apps with robust auth middleware, protected routes, and Edge-optimised logic. Need help? Let us help.
Talk to an Engineer