DEV3 Technologies home

DEV3 Developer Forum

How do I protect routes with Next.js middleware, and what is proxy.ts?

Next.js helpSolved0 views
dev3 ·

I want to redirect unauthenticated users from /dashboard to /login. I read that middleware.ts was renamed in Next.js 16. What should I use and what are the limits?

#nextjs#middleware#auth

0

1 reply

dev3 · Accepted answer

Middleware runs before a request is completed and can redirect, rewrite, set headers or cookies. In Next.js 16 the file convention middleware.ts was renamed to proxy.ts (function proxy instead of middleware) to clarify its role as a network-boundary layer. On Next 15 and earlier keep middleware.ts. middleware.ts still works in 16 but is deprecated, and proxy.ts runs on the Node.js runtime (the Edge runtime is not supported in proxy). Check the upgrade guide for your version; a codemod exists for the rename (npx @next/codemod@canary middleware-to-proxy .).

// middleware.ts (Next 15) , same body in proxy.ts on Next 16 with `export function proxy`
import { NextResponse, type NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const session = req.cookies.get("session")?.value;
  if (!session && req.nextUrl.pathname.startsWith("/dashboard")) {
    const url = new URL("/login", req.url);
    url.searchParams.set("next", req.nextUrl.pathname);
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*"],
};

Limits

  • Keep it fast: it runs on every matched request. Use matcher to skip _next/static, images and API routes you do not need.
  • In Next 15 middleware runs on the Edge runtime by default (Node.js runtime is stable from 15.5 via export const config = { runtime: "nodejs" }), so by default no Node-only modules (no Mongoose, fs). Verify a JWT with a library that supports Web Crypto (for example jose) or just check cookie presence.
  • It is an optimistic check only. A cookie can exist and still be invalid.

Defence in depth

Always re-check the session in the server component, route handler or server action that returns the data. Middleware is not a replacement for authorisation, especially after the March 2025 middleware bypass advisory (CVE-2025-29927) which was fixed in patched releases, so stay on current patch versions.

Pitfall: redirect loops happen when /login is covered by the matcher. Exclude it explicitly.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.