Skip to main content
0 reactions

How to Protect a Next.js Route Handler with Better Auth

A dark purple card titled Protect a Route Handler, labelled Better Auth How-to, with a four-step flow: GET /api/me, auth.api.getSession(), no session answers 401, a session answers with JSON.
Protect a Next.js route handler with Better Auth.

A route handler is an API route in Next.js: a route.ts file that answers with data. To protect one with Better Auth, read the session from the request and answer with status 401 when there isn’t one.

The short answer: in GET(request), call auth.api.getSession({ headers: request.headers }), and return Response.json(…, { status: 401 }) when it’s null.

Syntax

SyntaxTypeScript
export async function GET(request: Request) {
  const session = await auth.api.getSession({
    headers: request.headers,
  });

  if (!session) {
    return Response.json(<error>, { status: 401 });
  }

  return Response.json(<data>);
}
  • GET answers GET requests. Use POST, PUT and so on for other methods.
  • request.headers are the headers of the request, with the session cookie.
  • Response.json(<error>, { status: 401 }) sends an error object with the status 401, Unauthorized.
  • Response.json(<data>) sends the data to signed-in callers.

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

Step 1: Create the Route Handler

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). It gets an API route at /api/me that returns the signed-in person’s name and email address. Create app/api/me/route.ts:

app/api/me/route.tsTypeScript
import { auth } from "@/lib/auth";

export async function GET(request: Request) {
  const session = await auth.api.getSession({
    headers: request.headers,
  });

  if (!session) {
    return Response.json({ error: "Not signed in" }, { status: 401 });
  }

  return Response.json({
    name: session.user.name,
    email: session.user.email,
  });
}
  • A route handler receives the request, so its headers go straight to getSession.
  • Without a session, the route answers with { error: "Not signed in" } and status 401.
  • With one, it answers with the user’s name and email address.

Step 2: Call It Signed In and Signed Out

Signed in as Alex, open http://localhost:3000/api/me:

A browser showing the JSON reply name Alex Rivera and email alex@example.com, under a Pretty print checkbox.
The route’s reply for a signed-in visitor.

In a browser where nobody is signed in, the same address answers with the error:

A browser showing the JSON reply error: Not signed in.
Without a session, the route answers with status 401.

Terminal shows both requests, the second with status 401:

Output (the lines that matter)Plain text
 GET /api/me 200 in 50ms (next.js: 24ms, application-code: 26ms)
 GET /api/me 401 in 11ms (next.js: 5ms, application-code: 6ms)

Common Mistakes

MistakeWhat happensDo this instead
Redirecting to the sign-in pagePrograms that call the API get a web page instead of an errorAnswer with status 401
Returning the whole sessionTokens and other session details reach the callerReturn only the fields the caller needs
Checking the session only in proxy.tsA made-up cookie gets throughCheck it in the route handler too

Troubleshooting

ProblemCauseFix
The route always answers 401The request has no session cookie, for example from another site or a scriptCall it from the signed-in browser, or send the cookie with the request
404 instead of JSONThe file isn’t at app/api/me/route.tsCheck the folder names

FAQ

Why 401 and not 403?

401, Unauthorized, means the caller isn’t signed in. 403, Forbidden, is for a signed-in caller who isn’t allowed to do something.

Do I need headers() from next/headers here?

No. A route handler gets the request itself, so request.headers is enough.

Conclusion

Read the session from request.headers, answer with 401 when it’s missing, and return only what the caller needs. That’s a protected route handler.

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