Where do you define middleware in Next.js?

Create a single proxy.ts (or proxy.js) file in the project root, next to app/ and pages/, or inside src/ if you use a src directory. Before Next.js 16 the file was middleware.ts in the same location. Only one such file is supported per project.

Location rules

  • my-app/proxy.ts when app/ is at the root.
  • my-app/src/proxy.ts when you use src/app.
  • Not inside app/: a proxy.ts there is not picked up.
  • With custom pageExtensions like .page.tsx, name it proxy.page.ts.

Organizing larger logic

Only one file runs, but it can import modules. Split concerns into functions (handleAuth, handleLocale, handleAbTest) in a lib/proxy/ folder and call them in order from proxy.ts. Return as soon as one of them produces a response.

Exports

  • The function: a named proxy export or a default export.
  • Optional config with a matcher, which must be statically analyzable (literal strings or objects).

Execution scope

It runs for every request that matches, including RSC requests for client navigations and Server Function POSTs on matched paths. Without a matcher it also runs for static files and images, so add a negative matcher.

Code example

tsx
1// Project layout
2// my-app/
3// ├── src/
4// │ ├── app/
5// │ ├── lib/proxy/auth.ts
6// │ ├── lib/proxy/locale.ts
7// │ └── proxy.ts <- here when using src/
8// └── next.config.ts
9
10// src/proxy.ts
11import { NextResponse, type NextRequest } from "next/server";
12import { handleAuth } from "@/lib/proxy/auth";
13import { handleLocale } from "@/lib/proxy/locale";
14
15export function proxy(request: NextRequest) {
16 // Each handler returns a Response to stop, or undefined to continue
17 return handleAuth(request) ?? handleLocale(request) ?? NextResponse.next();
18}
19
20export const config = {
21 matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
22};

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app