Skip to main content
0 reactions

How to Protect Routes with proxy.ts in Next.js and Better Auth

A dark purple card titled Protect Routes with proxy.ts, labelled Better Auth How-to, with a four-step flow: request /dashboard, proxy.ts checks for a session cookie, no cookie redirects to /sign-in, a cookie opens the page.
Protect routes with proxy.ts and Better Auth.

Next.js 16 runs proxy.ts before it starts on a page. With Better Auth’s getSessionCookie, it can send visitors who have no session cookie to the sign-in page before the page does any work.

The short answer: in proxy.ts, redirect to /sign-in when getSessionCookie(request) returns null, and list the protected paths in config.matcher. Keep a full session check in the page too.

Syntax

SyntaxTypeScript
export function proxy(request: NextRequest) {
  if (!getSessionCookie(request)) {
    return NextResponse.redirect(new URL("<sign-in path>", request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["<path>"],
};
  • proxy is the function Next.js calls for each matching request. It gets the request as request.
  • getSessionCookie(request) comes from better-auth/cookies. It returns Better Auth’s session cookie, or null when the request has none.
  • NextResponse.redirect sends the visitor to <sign-in path>. NextResponse.next() lets the request continue.
  • matcher lists the <path> values the proxy runs on.

See Next.js’s proxy.js (opens in a new tab) reference and Better Auth’s Next.js integration (opens in a new tab) page.

Prerequisites

  • Next.js 16 or later. Earlier versions call this file middleware.ts and the function middleware.

Step 1: Create proxy.ts

The example is a small Next.js app with Better Auth and email and password sign-in, and one person, Alex Rivera (alex@example.com). Its /dashboard page should only open for signed-in people. In the project folder, next to package.json, create proxy.ts:

proxy.tsTypeScript
import { getSessionCookie } from "better-auth/cookies";
import { type NextRequest, NextResponse } from "next/server";

export function proxy(request: NextRequest) {
  const sessionCookie = getSessionCookie(request);

  if (!sessionCookie) {
    return NextResponse.redirect(new URL("/sign-in", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard"],
};
  • getSessionCookie only checks that the cookie is there. It doesn’t ask the database, so it’s fast.
  • new URL("/sign-in", request.url) builds the full sign-in address from the request’s own address.
  • matcher: ["/dashboard"] makes the proxy run only for the dashboard.

Step 2: Try It Signed Out and Signed In

In a browser where nobody is signed in, open http://localhost:3000/dashboard. The proxy answers with a redirect, and the sign-in page opens:

A Sign in page with empty Email and Password fields and a Sign in button, reached by opening the dashboard without a session cookie.
proxy.ts sent the signed-out visitor here.

Sign in and open the dashboard again. It opens, and the line Next.js prints in Terminal shows the time the proxy took:

Output (the lines that matter)Plain text
 GET /dashboard 200 in 547ms (next.js: 263ms, proxy.ts: 46ms, application-code: 238ms)

Note: anyone can send a made-up cookie, so this check alone protects nothing. Better Auth’s docs recommend it only for quick redirects, with the real check, auth.api.getSession, in the page or route itself.

Common Mistakes

MistakeWhat happensDo this instead
Relying on proxy.ts aloneA made-up session cookie gets past itAlso check the session in the page with auth.api.getSession
Leaving out matcherThe proxy runs on every request, including scripts and imagesList the paths to protect
Naming the file middleware.ts in Next.js 16It’s the old name for this fileName it proxy.ts and the function proxy

Troubleshooting

ProblemCauseFix
The dashboard opens for a visitor who isn’t signed inThe path isn’t in matcherAdd it to matcher
Signed-in people are sent to sign inYou changed the cookie name or prefix in Better AuthPass the same cookieName or cookiePrefix to getSessionCookie

FAQ

Can proxy.ts check the whole session?

Yes. In Next.js 16 it runs on Node.js, so it can call auth.api.getSession. That adds a database query to every request it matches, which is why the cookie check is the usual choice there.

Why does the request line show proxy.ts?

Next.js lists the time each part took. proxy.ts: 46ms means the proxy ran for that request.

Conclusion

proxy.ts with getSessionCookie turns away visitors without a session cookie before Next.js starts on the page. Keep the full session check in the page, too.

Additional Resources

Better Auth, Next.js and other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by Better Auth, Inc. or Vercel.

0 comments