In Next.js 16, middleware.ts was renamed to proxy.ts. The idea is still the same: run code before a request is completed. I usually think of Proxy as a checkpoint between the request and your app:
Request → proxy.ts → Next.js route
Proxy can inspect an incoming request and decide what happens next. For example, you can redirect, rewrite URLs, modify headers, or return a response directly. A simple redirect looks like this:
import { NextResponse } from 'next/server'import type { NextRequest } from 'next/server'export function proxy(request: NextRequest) {return NextResponse.redirect(new URL('/home', request.url))}
You usually don’t want Proxy to run for every route. Use matcher to limit it:
export const config = {matcher: '/admin/:path*',}
Now Proxy runs for /admin and nested routes, which is useful for things like checking a cookie before accessing an admin area.
Sitemaps, robots.txt, API calls and Next.js build files don’t need any proxy logic, so they go straight through:
if (pathname === "/sitemap.xml" ||pathname === "/robots.txt" ||pathname === "/favicon.ico" ||pathname.startsWith("/api/") ||pathname.startsWith("/_next/")) {return NextResponse.next();}
Visitors to /admin/... without auth cookies are redirected to /admin/login?redirect=.... Logged-in users who open the login page are sent to /admin.
function handleAdminAuth(request: NextRequest) {const { pathname } = request.nextUrl;const isLoginPage = pathname === "/admin/login";// UX-only gate: FastAPI remains the real security boundary.const authenticated = hasAuthCookies(request.cookies);if (!authenticated && !isLoginPage) {const loginUrl = request.nextUrl.clone();loginUrl.pathname = "/admin/login";loginUrl.search = "";if (pathname !== "/admin") {loginUrl.searchParams.set("redirect", pathname);}return NextResponse.redirect(loginUrl);}// ...}
Note the comment: this check is only for user experience. It only looks for the cookies, it doesn’t verify them. The FastAPI backend does the real security checks on every request.
Paths without a language get a permanent redirect. /plants/x becomes /vi/plants/x with a 308 redirect, so Google moves the page’s ranking to the /vi URL.
const hasLocale = locales.some((locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`));if (!hasLocale) {const url = request.nextUrl.clone();url.pathname = `/vi${pathname}`;return NextResponse.redirect(url, 308);}