Fix Middleware Not Working in Next.js: Common Causes & Solutions
Middleware in Next.js must be placed in the
middleware.ts or middleware.js file at the root or app directory and export a middleware function. Ensure you use the correct NextResponse and return it properly; otherwise, middleware won't run as expected.Why This Happens
Middleware in Next.js often doesn't work because it is either not placed in the correct file or directory, or the exported function is missing or incorrectly implemented. Another common cause is forgetting to return a NextResponse object, which is required to continue the request lifecycle.
typescript
import { NextResponse } from 'next/server'; export function middleware(req) { console.log('Middleware running'); // Missing return statement return NextResponse.next(); }
Output
Middleware running (logged in server console), request continues normally.
The Fix
Place your middleware code in a file named middleware.ts or middleware.js at the root of your project or inside the app directory. Export a middleware function that takes a request and returns a NextResponse. Always return the response to ensure middleware runs correctly.
typescript
import { NextResponse } from 'next/server'; export function middleware(request) { console.log('Middleware running'); return NextResponse.next(); }
Output
Middleware running (logged in server console), request continues normally.
Prevention
To avoid middleware issues, always:
- Use the correct file name
middleware.tsormiddleware.jsat the root orappfolder. - Export a properly defined
middlewarefunction that returnsNextResponse. - Test middleware behavior by logging or debugging.
- Keep Next.js updated to the latest stable version to benefit from fixes.
Related Errors
Other common middleware-related errors include:
- 404 on middleware file: Happens if the middleware file is misplaced or misnamed.
- Middleware not running on specific routes: Check your
matcherconfiguration inmiddleware.ts. - Using unsupported APIs inside middleware: Middleware runs on the edge, so some Node.js APIs are unavailable.
Key Takeaways
Middleware must be in a file named middleware.ts or middleware.js at the root or app directory.
Always export a middleware function that returns a NextResponse object.
Returning NextResponse.next() continues the request properly.
Check your middleware matcher to control which routes it runs on.
Keep Next.js updated and test middleware with console logs or debugging.