Skip to content

Better Auth#

Install#

npm install better-auth

Auth Configuration#

// lib/auth.ts
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "./db";

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg",
  }),
  emailAndPassword: {
    enabled: true,
  },
});

API Route Handler#

// app/api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { GET, POST } = toNextJsHandler(auth);

Client SDK Setup#

// lib/auth-client.ts
import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient({
  baseURL: process.env.BETTER_AUTH_URL,
});

export const { signIn, signUp, signOut, useSession } = authClient;

Signup (Client)#

'use client'

import { signUp } from "@/lib/auth-client";

const handleSignup = async () => {
  await signUp.email({
    email: "user@example.com",
    password: "password123",
    name: "John Doe",
  });
};

Login (Client)#

'use client'

import { signIn } from "@/lib/auth-client";

const handleLogin = async () => {
  await signIn.email({
    email: "user@example.com",
    password: "password123",
  });
};

Logout (Client)#

'use client'

import { signOut } from "@/lib/auth-client";

const handleLogout = async () => {
  await signOut();
};

Session (Server Component)#

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

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

  return <div>Hello {session?.user.name}</div>;
}

Session (Client Component)#

'use client'

import { useSession } from "@/lib/auth-client";

function Profile() {
  const { data: session } = useSession();
  return <div>{session?.user.email}</div>;
}

Protected Layout (Server)#

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

export default async function Layout({ children }) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) redirect("/login");

  return <>{children}</>;
}