Site icon JD Bots

How to Protect a Page in a Next.js Server Component with Better Auth

A dark purple card titled Protect a Page in Next.js, labelled Better Auth How-to, with a shield and padlock and three facts: auth.api.getSession(), inside Suspense, and redirect to /sign-in.

Protect a page in a Next.js server component with Better Auth.

To keep a Next.js page private with Better Auth, read the session on the server, inside the page itself, and send anyone without one to the sign-in page. Hiding a link in the browser isn’t enough: the check has to run on the server.

The short answer: in a server component, call auth.api.getSession({ headers: await headers() }) inside <Suspense>, and redirect("/sign-in") when it returns null.

Syntax

Syntax

const session = await auth.api.getSession({
  headers: await headers(),
});

if (!session) {
  redirect("<sign-in path>");
}

Better Auth’s Next.js integration page documents this pattern, and Next.js documents headers and redirect.

Step 1: Read the Session in the Page

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 has a /dashboard page that greets the signed-in person. Create app/dashboard/page.tsx:

app/dashboard/page.tsx

import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { auth } from "@/lib/auth";

export default function DashboardPage() {
  return (
    <main className="mx-auto w-full max-w-xl flex-1 px-6 py-12">
      <h1 className="text-2xl font-semibold">Dashboard</h1>
      <Suspense fallback={<p className="mt-4">Loading…</p>}>
        <Greeting />
      </Suspense>
    </main>
  );
}

async function Greeting() {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    redirect("/sign-in");
  }

  return <p className="mt-4">Hello, {session.user.name}!</p>;
}

Step 2: Open the Page

Sign in as Alex and open http://localhost:3000/dashboard:

The dashboard, for a signed-in visitor.

Now open the same address in a browser where nobody is signed in: the sign-in page opens instead. The dashboard never shows its greeting to a visitor without a session.

Common Mistakes

MistakeWhat happensDo this instead
Hiding the page’s link instead of checking the sessionAnyone who types the address still sees the pageCheck the session in the page itself
Checking only a cookie, for example in proxy.tsA made-up or ended session gets past itCheck with auth.api.getSession in the page

Troubleshooting

ProblemCauseFix
npm run build stops with “Next.js encountered uncached or runtime data during prerendering”The session is read outside <Suspense>Read it in a component inside <Suspense>, as above
The page always sends you to sign inThere’s no session in this browserSign in first, in the same browser

FAQ

Can I use this in a layout?

Yes, but keep the session read in a component inside <Suspense>, not at the layout’s top level, so the rest of the page doesn’t wait for it.

Is a redirect in a server component a real redirect?

Inside <Suspense> the page is streamed, so Next.js sends the redirect to the browser, which then opens the sign-in page. The greeting itself is never sent.

Conclusion

Reading the session with auth.api.getSession in a server component, inside <Suspense>, and redirecting when it’s missing keeps a Next.js page private.

Additional Resources

Related

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.

Exit mobile version