Where Should Your `middleware.ts` File Be Located in a Next.js 15 Project?

Middleware in Next.js is a powerful tool for handling route protection, authentication, and redirects before the page even loads.

Unlike solutions that rely on useEffect or useRouter, middleware runs at the edge, ensuring a seamless experience without flickering UI issues.

Problem: Middleware Not Working Due to Incorrect Placement

If your middleware.ts file isn’t working, it’s likely placed incorrectly in your project structure.

Solution: Correct Middleware Placement Based on Your Project Structure

If You Are Using the src Directory:

Place middleware.ts inside src, at the same level as the app folder:

/src
  ├── app/
  ├── middleware.ts

If You Are Not Using the src Directory:

Place middleware.ts in the root of your project, at the same level as the pages or app folder:

/
  ├── app/ (or pages/)
  ├── middleware.ts

Key Takeaways

Example Middleware File

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const isAuthenticated = Boolean(req.cookies.get("token"));

  if (!isAuthenticated) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
  return NextResponse.next();
}

Common Questions (FAQs)

1. What happens if I place middleware.ts in the wrong directory?
Next.js won’t recognize it, meaning your middleware logic won’t execute.

2. Can I have multiple middleware.ts files?
No, Next.js only supports a single middleware.ts file.

However, you can modularize it by importing functions from other files.

3. Can middleware protect API routes?
No, middleware is only for handling requests to pages, not API routes (/api).

Use API route handlers (app/api) for API-specific protection.

4. How can I verify my middleware is running correctly?
Add a console.log inside your middleware function and check your server logs to ensure it executes.

For more details, check out the Next.js middleware documentation.