Skip to main content
0 reactions

How to Check the Session in a Next.js Server Action with Better Auth

A dark purple card titled Check the Session in a Server Action, labelled Better Auth How-to, with a shield and padlock and three facts: use server, getSession() first, and no session means sign in.
Check the Better Auth session in a Next.js server action.

A Next.js server action runs on the server when a form is sent, and Next.js gives it an address anyone can call. So a server action that changes something checks the Better Auth session itself, before it does anything.

The short answer: start the action with auth.api.getSession({ headers: await headers() }), and redirect to the sign-in page when there’s no session.

Syntax

SyntaxTypeScript
"use server";

export async function <actionName>(formData: FormData) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

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

  // the change, for session.user
}
  • "use server" at the top of the file makes its exported functions server actions.
  • <actionName> is your action’s name. A form passes its fields in formData.
  • auth.api.getSession returns the session, or null when the caller isn’t signed in.
  • redirect("<sign-in path>") stops the action for anyone without a session.

See Better Auth’s Next.js integration (opens in a new tab) page and Next.js’s Authentication (opens in a new tab) guide, which says to treat server actions like public API endpoints.

Step 1: Write the Server Action

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 profile page has a form that changes the display name. Create app/profile/actions.ts:

app/profile/actions.tsTypeScript
"use server";

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

export async function updateName(formData: FormData) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

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

  await auth.api.updateUser({
    body: { name: String(formData.get("name")) },
    headers: await headers(),
  });

  redirect("/dashboard");
}
  • The session check comes first, so nothing changes for a caller who isn’t signed in.
  • auth.api.updateUser saves the new name for the signed-in user, found from the same headers.
  • redirect("/dashboard") shows the result.

Step 2: Call It from a Form

Create app/profile/page.tsx, with a form whose action is the server action:

app/profile/page.tsxTypeScript
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { auth } from "@/lib/auth";
import { updateName } from "./actions";

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

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

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

  return (
    <form action={updateName} className="mt-6 flex flex-col gap-4">
      <label className="flex flex-col gap-1 text-sm">
        Name
        <input
          name="name"
          defaultValue={session.user.name}
          required
          className="rounded border border-zinc-300 px-3 py-2"
        />
      </label>
      <button
        type="submit"
        className="rounded bg-zinc-900 px-4 py-2 text-white"
      >
        Save
      </button>
    </form>
  );
}

Step 3: Try It

Open http://localhost:3000/profile, type a new name and click Save:

A Profile page with a Name field containing Alex R. Rivera and a Save button.
The form that calls the server action.

The dashboard opens with the new name:

A page titled Dashboard with the line Hello, Alex R. Rivera!
The server action saved the new name.

Next.js prints the action it ran:

Output (the lines that matter)Plain text
 POST /profile 200 in 78ms (next.js: 0.7ms, application-code: 78ms)
  └─ ƒ updateName({}) in 18ms profile/actions.ts

Then I opened the form again, ended Alex’s session on the server (as an expired session or a sign-out elsewhere would), and clicked Save. The action found no session and sent the browser to the sign-in page, without changing the name.

Common Mistakes

MistakeWhat happensDo this instead
Trusting that only signed-in people can see the formAnyone can call the action directlyCheck the session inside the action
Taking a user ID from the formA caller can change someone else’s dataUse session.user from the session
Leaving out headersgetSession can’t see the cookie and returns nullPass headers: await headers()

Troubleshooting

ProblemCauseFix
Saving always sends you to sign inThe session ended, or you’re signed in in another browserSign in again in this browser
The name changes, but parts of the page show the old oneThose parts were rendered before the changeRedirect after the change, or call router.refresh() in the browser

FAQ

Does a server action need nextCookies?

Only when it calls a Better Auth function that sets cookies, such as signing in or out. Changing the name doesn’t.

Can I return an error instead of redirecting?

Yes. A server action can return a value for the form to show. A redirect is simplest when the caller isn’t signed in.

Conclusion

Start every server action that changes data with auth.api.getSession, and stop when it’s null. The form’s page being private doesn’t protect the action.

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