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.tswhenapp/is at the root.my-app/src/proxy.tswhen you usesrc/app.- Not inside
app/: aproxy.tsthere is not picked up. - With custom
pageExtensionslike.page.tsx, name itproxy.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
proxyexport or a default export. - Optional
configwith amatcher, 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
1// Project layout2// my-app/3// ├── src/4// │ ├── app/5// │ ├── lib/proxy/auth.ts6// │ ├── lib/proxy/locale.ts7// │ └── proxy.ts <- here when using src/8// └── next.config.ts910// src/proxy.ts11import { NextResponse, type NextRequest } from "next/server";12import { handleAuth } from "@/lib/proxy/auth";13import { handleLocale } from "@/lib/proxy/locale";1415export function proxy(request: NextRequest) {16 // Each handler returns a Response to stop, or undefined to continue17 return handleAuth(request) ?? handleLocale(request) ?? NextResponse.next();18}1920export 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.