Authentication with Better Auth (and Auth.js)
Better Auth is an open-source sign-in library that runs on your own server and stores accounts in your own database. It covers every Pulze sign-in page, including two-step, magic links, workspaces, SSO and passkeys.
Why not Auth.js (NextAuth)? Auth.js is now maintained by the Better Auth team, and they recommend Better Auth for new projects. Auth.js has no built-in sign-up, password reset or two-step, so you'd write those yourself. If you already use Auth.js, see the last section.
Read Authentication first: it explains the adapter these steps fill in.
Time: about an hour with a database ready.
What Better Auth covers
| Pulze feature | Better Auth | Notes |
|---|---|---|
| Email + password | ✓ emailAndPassword |
|
| Google, GitHub, Apple | ✓ socialProviders |
|
| Magic link | ✓ magicLink plugin |
You send the email |
| Forgot / reset password | ✓ link-based | Keep resetWith: "link"; you send the email |
| Two-step: app code (TOTP) | ✓ twoFactor plugin |
|
| Two-step: text message | ✓ twoFactor OTP |
You send the SMS |
| Two-step: backup codes | ✓ | |
| SSO (SAML / OIDC) | ✓ @better-auth/sso |
|
| Passkey on lock screen | ✓ @better-auth/passkey |
|
| Workspaces and invites | ✓ organization plugin |
You send the invite email |
1. Install
You need a database. Postgres is used below; SQLite, MySQL, Prisma and Drizzle work too (see Better Auth's installation guide).
pnpm add better-auth @better-auth/sso @better-auth/passkey pg
Add to .env.local (never commit it):
BETTER_AUTH_SECRET= # 32+ random characters: openssl rand -base64 32
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=postgres://user:password@localhost:5432/acme
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
GITHUB_CLIENT_ID=...
GITHUB_CLIENT_SECRET=...
Each social provider gives you an ID and secret in its developer console.
The callback URL to register there is
http://localhost:3000/api/auth/callback/google (and /github, /apple),
plus the same with your live domain.
2. The server (Next.js)
Create lib/auth.ts:
import "server-only"
import { passkey } from "@better-auth/passkey"
import { sso } from "@better-auth/sso"
import { betterAuth } from "better-auth"
import { nextCookies } from "better-auth/next-js"
import { magicLink, organization, twoFactor } from "better-auth/plugins"
import { Pool } from "pg"
import { siteConfig } from "@pulze/config"
import { sendEmail, sendSms } from "./send" // your email/SMS sender (step 5)
export const auth = betterAuth({
appName: siteConfig.name, // shown in authenticator apps
database: new Pool({ connectionString: process.env.DATABASE_URL }),
emailAndPassword: {
enabled: true,
revokeSessionsOnPasswordReset: true, // matches "signed out on all other devices"
sendResetPassword: async ({ user, url }) => {
await sendEmail(user.email, `Reset your ${siteConfig.name} password`, url)
},
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
},
},
plugins: [
twoFactor({
otpOptions: {
sendOTP: async ({ user, otp }) => {
await sendSms(user, `Your ${siteConfig.name} code is ${otp}`)
},
},
}),
magicLink({
sendMagicLink: async ({ email, url }) => {
await sendEmail(email, `Your ${siteConfig.name} sign-in link`, url)
},
}),
organization({
sendInvitationEmail: async ({ email, inviter, organization, id }) => {
const link = `${process.env.BETTER_AUTH_URL}/sign-up?invite=${id}`
await sendEmail(
email,
`${inviter.user.name} invited you to ${organization.name}`,
link
)
},
}),
sso(),
passkey({ rpName: siteConfig.name }),
nextCookies(), // keep this last
],
})
Delete the plugins for options you turned off in siteConfig.auth.
Create app/api/auth/[...all]/route.ts:
import { toNextJsHandler } from "better-auth/next-js"
import { auth } from "@/lib/auth"
export const { GET, POST } = toNextJsHandler(auth)
Create the tables:
npx auth@latest migrate
Run it again whenever you add or remove a plugin. (With Prisma or Drizzle,
use npx auth@latest generate and your own migration tool instead.)
Vite
A Vite app has no server, so Better Auth runs on your API (Node with Hono,
Express, Fastify and others: see Better Auth's integration guides). Use the
same auth.ts, mount its handler at /api/auth/*, add the Vite address to
trustedOrigins, and point the client below at it with baseURL.
3. Write the adapter
Create src/data/auth/better-auth.ts:
import { passkeyClient } from "@better-auth/passkey/client"
import { ssoClient } from "@better-auth/sso/client"
import {
magicLinkClient,
organizationClient,
twoFactorClient,
} from "better-auth/client/plugins"
import { createAuthClient } from "better-auth/react"
import { setPendingEmail } from "./pending"
import { AuthError, type AuthAdapter } from "./types"
export const authClient = createAuthClient({
// Same site (Next.js): leave out. Separate API (Vite): its address.
// baseURL: import.meta.env.VITE_API_URL,
plugins: [
twoFactorClient(),
magicLinkClient(),
organizationClient(),
ssoClient(),
passkeyClient(),
],
})
type BaError = { status: number; code?: string; message?: string } | null
/** Turns a Better Auth error into the screens Pulze knows. */
function check(error: BaError, when: "sign-in" | "sign-up" | "code" | "reset") {
if (!error) return
if (error.status === 429)
throw new AuthError("Too many tries. Wait a few minutes.", "too-many-tries", 0)
if (when === "sign-in" && error.status === 401)
throw new AuthError("That email and password don't match.", "wrong-password")
if (
when === "sign-up" &&
(error.status === 422 || error.code === "USER_ALREADY_EXISTS")
)
throw new AuthError("There's already an account with this email.", "email-taken")
if (when === "code" && (error.status === 401 || error.status === 400))
throw new AuthError("That code isn't right.", "wrong-code")
if (when === "reset" && error.status === 400)
throw new AuthError("This link has expired.", "link-expired")
throw new AuthError(error.message ?? "Something went wrong.", "unknown")
}
let usingSms = false
export const betterAuthAdapter: AuthAdapter = {
async currentUser() {
const { data } = await authClient.getSession()
if (!data) return null
const { id, name, email } = data.user
return { id, name, email, hue: 262 }
},
async signIn({ email, password, remember }) {
const { data, error } = await authClient.signIn.email({
email,
password,
rememberMe: remember,
})
check(error, "sign-in")
if (data && "twoFactorRedirect" in data && data.twoFactorRedirect) {
setPendingEmail(email)
return { next: "two-step", email }
}
return { next: "done" }
},
// These three leave the page for the provider and come back signed in.
async signInWithProvider(provider) {
const { error } = await authClient.signIn.social({ provider, callbackURL: "/" })
check(error, "sign-in")
return { next: "done" }
},
async signInWithSso(email) {
const { error } = await authClient.signIn.sso({ email, callbackURL: "/" })
check(error, "sign-in")
return { next: "done" }
},
async sendMagicLink(email) {
const { error } = await authClient.signIn.magicLink({ email, callbackURL: "/" })
check(error, "sign-in")
},
async signUp({ firstName, lastName, email, password }) {
const { error } = await authClient.signUp.email({
name: `${firstName} ${lastName}`,
email,
password,
})
check(error, "sign-up")
},
async createWorkspace({ name, slug, size }) {
const { error } = await authClient.organization.create({
name,
slug,
metadata: { size },
})
check(error, "sign-up")
},
async inviteTeam(emails) {
for (const email of emails) {
const { error } = await authClient.organization.inviteMember({
email,
role: "member",
})
check(error, "sign-up")
}
},
async sendPasswordReset(email) {
const { error } = await authClient.requestPasswordReset({
email,
redirectTo: "/reset-password",
})
check(error, "reset")
},
/** Better Auth adds ?error=INVALID_TOKEN to the link when it's no good. */
async checkResetToken() {
if (new URLSearchParams(window.location.search).get("error"))
throw new AuthError("This link has expired.", "link-expired")
return { email: "" } // Better Auth doesn't say whose link it is; the page copes.
},
async resetPassword(token, password) {
const { error } = await authClient.resetPassword({ token, newPassword: password })
check(error, "reset")
},
async verifyCode(code, trustDevice) {
const { error } = usingSms
? await authClient.twoFactor.verifyOtp({ code, trustDevice })
: await authClient.twoFactor.verifyTotp({ code, trustDevice })
check(error, "code")
usingSms = false
setPendingEmail(null)
},
async verifyBackupCode(code) {
const { error } = await authClient.twoFactor.verifyBackupCode({ code })
check(error, "code")
setPendingEmail(null)
},
async sendCodeBySms() {
const { error } = await authClient.twoFactor.sendOtp()
check(error, "code")
usingSms = true
return "your phone"
},
async unlock(password) {
const { data } = await authClient.getSession()
if (!data) throw new AuthError("Sign in again.", "unknown")
const { error } = await authClient.signIn.email({ email: data.user.email, password })
check(error, "sign-in")
},
async unlockWithPasskey() {
const { error } = await authClient.signIn.passkey()
check(error, "sign-in")
},
async signOut() {
await authClient.signOut()
},
}
Switch Pulze to it in src/data/auth/index.ts:
import { betterAuthAdapter } from "./better-auth"
export const auth: AuthAdapter = betterAuthAdapter
Apple: add apple: { clientId, clientSecret } to socialProviders.
Apple's secret is a signed key that expires; follow Better Auth's
Apple guide.
Invites: the invite link goes to /sign-up?invite=<id>. After the
person signs up, call
authClient.organization.acceptInvitation({ invitationId }) with that id;
the simplest place is the end of signUp in the adapter, reading the id
from window.location.search.
4. Protect the app pages (Next.js)
Create proxy.ts next to app/:
import { getSessionCookie } from "better-auth/cookies"
import { NextResponse, type NextRequest } from "next/server"
const PUBLIC = [
"/sign-in",
"/sign-up",
"/forgot-password",
"/reset-password",
"/two-step",
"/maintenance",
"/api/auth",
]
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
if (PUBLIC.some((p) => pathname.startsWith(p))) return
if (!getSessionCookie(request)) {
const url = new URL("/sign-in", request.url)
url.searchParams.set("from", pathname)
return NextResponse.redirect(url)
}
}
export const config = { matcher: ["/((?!_next|favicon|icon|.*\\..*).*)"] }
This only checks that a cookie exists. Before returning private data in a route handler or server action, check the session for real:
import { headers } from "next/headers"
import { auth } from "@/lib/auth"
const session = await auth.api.getSession({ headers: await headers() })
if (!session) return new Response("Signed out", { status: 401 })
Vite: use the route guard in
Authentication; your API
checks the session with auth.api.getSession the same way.
5. Sending email and texts
Better Auth gives you the link or code; you send it. A minimal sender with
Resend (pnpm add resend):
// lib/send.ts
import "server-only"
import { Resend } from "resend"
const resend = new Resend(process.env.RESEND_API_KEY)
export async function sendEmail(to: string, subject: string, link: string) {
await resend.emails.send({
from: "Acme <no-reply@acme.io>",
to,
subject,
html: `<p><a href="${link}">${subject}</a></p><p>If you didn't ask for this, ignore this email.</p>`,
})
}
export async function sendSms(user: { email: string }, text: string) {
// Plug in your SMS provider (Twilio, MessageBird…). Until then, email it:
await resend.emails.send({
from: "Acme <no-reply@acme.io>",
to: user.email,
subject: text,
text,
})
}
Use the subjects and expiry times from the email table. Any provider works: Postmark, SES, SendGrid or plain SMTP with Nodemailer.
6. Turning on two-step and passkeys for a person
People turn these on from Settings › Security. Wire the buttons there to:
| Button | Call |
|---|---|
| Turn on authenticator app | authClient.twoFactor.enable({ password }), then show totpURI as a QR code |
| Show backup codes | authClient.twoFactor.generateBackupCodes({ password }) |
| Turn off two-step | authClient.twoFactor.disable({ password }) |
| Add a passkey | authClient.passkey.addPasskey({ name: "MacBook" }) |
7. Check it
-
npx auth@latest migrateran without errors. - Sign up, then see the new row in the
usertable. - Wrong password: "That email and password don't match."
- Sign in with Google and GitHub.
- Forgot password: the email link opens
/reset-password?token=…and the new password works. - Turn on two-step, sign out, sign in: you land on
/two-step. - Open
/apps/kanbanin a private window: you're sent to/sign-in?from=/apps/kanbanand come back after signing in.
Troubleshooting
| You see | Fix |
|---|---|
relation "user" does not exist |
Run npx auth@latest migrate. |
| Social sign-in returns "redirect_uri_mismatch" | Register …/api/auth/callback/<provider> for every address you use (localhost and live) in the provider's console. |
| Signed in, but every page sends you to sign-in | BETTER_AUTH_URL doesn't match the address in the browser, so the cookie is set for another domain. |
| Vite: requests blocked by CORS | Add the Vite address to trustedOrigins on the server, and allow credentials in your API's CORS settings. |
| No emails arrive | sendEmail threw: check the server log. With Resend, verify your sending domain first. |
Already on Auth.js
If your project already uses Auth.js (next-auth), keep it and write a
smaller adapter:
| Method | With Auth.js |
|---|---|
signIn |
signIn("credentials", { email, password, redirect: false }) from next-auth/react; error set = wrong password |
signInWithProvider |
signIn("google") / signIn("github") / signIn("apple") |
sendMagicLink |
signIn("resend", { email, redirect: false }) (needs a database adapter) |
currentUser |
getSession() from next-auth/react |
signOut |
signOut({ redirect: false }) |
signUp, reset, two-step, SSO |
Not built in: write your own route handlers, or turn those options off |
Protect pages with export { auth as proxy } from "@/auth" in proxy.ts,
and set authorized: ({ auth }) => !!auth in your Auth.js callbacks.