Next.jsMiddlewareError Fix2026 Updated

Next.js Middleware Not Working— Fixed [Complete Guide 2026]

Also covers: file location · matcher config · Edge Runtime · auth redirects · infinite redirect loops

January 20266 min readNext.js 14/15 · Edge Runtime

⚡ The Symptom

Error
// 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

middleware.ts ← must be at project root
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.

1

Check middleware.ts File Location

Most common cause — wrong directory
1 min
Correct project structure
my-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 run

If you use a src/ directory layout (src/app/ instead of app/), place middleware at src/middleware.ts — not at the project root.

2

Fix the Matcher Configuration

Middleware runs but not on expected routes
2 min

The matcher in the exported config controls which routes trigger the middleware. An overly restrictive matcher silently skips routes.

middleware.ts — matcher examples
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*"],
}
3

Always Return a Response

Middleware that returns undefined causes errors
1 min

Every 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.

middleware.ts — always return
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
}
4

Fix Auth Redirects and Infinite Loops

Protected routes redirecting to login and back
3 min

An 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.

middleware.ts — auth with no infinite loop
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).*)"],
}
5

Fix Edge Runtime Limitations

Node.js APIs crashing middleware
3 min

Middleware 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.

middleware.ts — Edge-compatible JWT verification
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

Frequently Asked Questions

Where should middleware.ts be placed in Next.js?+
middleware.ts must be at the root of your project — the same level as your package.json and next.config.ts. It should NOT be inside the /app or /pages directory. This is the most common mistake causing middleware to silently not run.
Why is my Next.js middleware not running on any routes?+
The two most common causes are: 1) middleware.ts is in the wrong location (must be at project root, not inside /app), and 2) the matcher config excludes all routes. Check both before debugging further.
How do I make middleware run on all routes?+
Export a config object with matcher: ['/(.*)']. This matches every path. To exclude static files and API routes, use a negative lookahead: matcher: ['/((?!_next/static|_next/image|favicon.ico|api/).*)'].
Can I use Node.js APIs in Next.js middleware?+
No. Middleware runs in the Edge Runtime, which is a lightweight JavaScript environment that does not support Node.js APIs like fs, path, crypto, or Buffer. Use only Web APIs (Request, Response, Headers, URL) and the next/server utilities.
Why does my middleware redirect loop infinitely?+
An infinite redirect loop happens when the redirect target URL also matches the middleware matcher, causing the middleware to redirect again. Exclude the login/redirect page from your matcher, or check the current URL inside the middleware before redirecting.
Can Next.js middleware read request body?+
No. Middleware cannot read the request body. It only has access to request headers, cookies, and the URL. For body-dependent logic (like validating a POST payload), use an API route or Server Action instead.

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