Skip to main content
0 reactions

How to Use the Better Auth nextCookies Plugin in Next.js

A dark purple card titled The nextCookies Plugin, labelled Better Auth How-to, with a shield and padlock and three facts: plugins with nextCookies(), cookies from server actions, and keep it last.
The Better Auth nextCookies plugin for Next.js server actions.

Better Auth functions such as signing in and out set cookies. Called from a Next.js server action, those cookies don’t reach the browser on their own. The nextCookies plugin passes them on.

The short answer: import nextCookies from better-auth/next-js and add plugins: [nextCookies()] to betterAuth(), as the last plugin.

Syntax

SyntaxTypeScript
import { nextCookies } from "better-auth/next-js";

export const auth = betterAuth({
  // your other settings
  plugins: [<other plugins>, nextCookies()],
});
  • nextCookies() sets every cookie a Better Auth call returns, through Next.js’s own cookies helper.
  • <other plugins> are any plugins you already use. Better Auth’s docs ask for nextCookies() to come last.

Better Auth documents it under “Server Action Cookies” on its Next.js integration (opens in a new tab) page.

Step 1: Sign In from a 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 log-in page signs in on the server, through a server action. Create app/login/actions.ts:

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

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

export async function signInAction(formData: FormData) {
  await auth.api.signInEmail({
    body: {
      email: String(formData.get("email")),
      password: String(formData.get("password")),
    },
  });

  redirect("/dashboard");
}

auth.api.signInEmail checks the email address and password and starts a session. Then create the page, app/login/page.tsx:

app/login/page.tsxTypeScript
import { signInAction } from "./actions";

export default function LoginPage() {
  return (
    <main className="mx-auto w-full max-w-sm flex-1 px-6 py-12">
      <h1 className="text-2xl font-semibold">Log in</h1>
      <form action={signInAction} className="mt-6 flex flex-col gap-4">
        <label className="flex flex-col gap-1 text-sm">
          Email
          <input
            name="email"
            type="email"
            required
            className="rounded border border-zinc-300 px-3 py-2"
          />
        </label>
        <label className="flex flex-col gap-1 text-sm">
          Password
          <input
            name="password"
            type="password"
            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"
        >
          Log in
        </button>
      </form>
    </main>
  );
}
A Log in page with the email alex@example.com, a hidden password and a Log in button.
A form whose action signs in on the server.

Step 2: Try It Without the Plugin

Without nextCookies, log in as Alex and click Log in. Better Auth starts the session on the server, but the session cookie never reaches the browser. The dashboard finds no session and sends you to the sign-in page.

Step 3: Add nextCookies

Open lib/auth.ts and add the plugin:

lib/auth.tsTypeScript
import { betterAuth } from "better-auth";
import { nextCookies } from "better-auth/next-js";
import { Pool } from "pg";

export const auth = betterAuth({
  database: new Pool({
    connectionString: process.env.DATABASE_URL,
  }),
  emailAndPassword: {
    enabled: true,
  },
  plugins: [nextCookies()],
});

Log in again. This time the cookie reaches the browser, and the dashboard opens with “Hello, Alex Rivera!”.

Common Mistakes

MistakeWhat happensDo this instead
Leaving out the pluginSign-in and sign-out in server actions don’t change the browser’s cookiesAdd nextCookies()
Expecting it to help in client componentsIt only affects server actionsIn the browser, the auth client sets its cookies itself

Troubleshooting

ProblemCauseFix
Logging in sends you back to sign innextCookies is missing, so no cookie was setAdd the plugin, then log in again
A wrong password stops the action with an errorOn the server, Better Auth throws an APIError when a call failsCatch it in the action (Better Auth’s isAPIError helps) and show a message

FAQ

Where does nextCookies go?

In the plugins list of betterAuth(), last, as Better Auth’s docs ask.

Does it change anything for useSession?

No. The auth client in the browser already sets its own cookies when you sign in through it.

Conclusion

If your server actions call Better Auth functions that set cookies, add nextCookies() as the last plugin. Without it, those calls work on the server but never reach the browser.

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