Protect Routes in proxy.ts
Medium · Proxy
In Next.js 16, **Proxy** (the file proxy.ts in the project root, called middleware.ts before v16) runs before a request reaches your pages. It exports a function proxy(request) and can redirect, rewrite, or let the request continue. Returning nothing (or NextResponse.next()) continues.
A common use is an **optimistic auth check**: only look at the session cookie and send logged-out visitors to the login page. (The real permission checks still belong in your pages and data layer.)
The request here is a small stand-in for NextRequest: request.nextUrl is a URL of the request and request.cookies.get(name) returns { name, value } or undefined.
Implement proxy(request):
- The user is logged in when the session cookie exists and its value is not empty.
- A path is protected when it equals one of PROTECTED or starts with it followed by / (/dashboard/reports yes, /dashboards no).
- Protected path + logged out: redirect to /login with the original pathname in a from search param (build it with new URL("/login", request.url) and url.searchParams.set("from", pathname)). Use Response.redirect(url, 307). (NextResponse.redirect(url) does the same and uses 307 by default.)
- /login + logged in: redirect to /dashboard (307).
- Otherwise return undefined.
The driver runProxy(url, cookies) is already written. It returns { action: "next" } or { action: "redirect", status, location }, where location is shown as a decoded path.
Next: Proxy Matcher Paths