In Part 2 you connected Better Auth to a Next.js app and a PostgreSQL database. Now people get to use it. In this part you add Better Auth email and password sign-in to Next.js: a sign-up page, a sign-in page, sign-out, and a header that shows who’s signed in.
By the end of this part, you’ll have:
- a sign-up page at
/sign-upthat creates an account and signs the new user in - a sign-in page at
/sign-in, with a clear message when the password is wrong - a header on every page that shows who’s signed in, with a Sign out button
- Lena Park, the Bookshop’s first customer, with her own account
This is Part 3 of the Better Auth Tutorial. The parts in Module A, Start Here:
- Part 1: What Is Better Auth?
- Part 2: Set Up Better Auth in Next.js with PostgreSQL
- Part 3: Sign Up and Sign In with Email and Password (you are here)
All parts of the Better Auth Tutorial
Module A: Start Here
- Part 1: What Is Better Auth?
- Part 2: Set Up Better Auth in Next.js with PostgreSQL
- Part 3: Sign Up and Sign In with Email and Password
Module B: Sessions and Users
- Part 4: Protect Pages, Server Actions and API Routes
- Part 5: Sessions: Expiry, Cookie Cache and Signing Out Everywhere
- Part 6: Users and Accounts: Custom Fields, Change Email and Delete Account
Module C: Email and Passwordless
- Part 7: Email Verification and Password Reset
- Part 8: Passwordless Sign-In: Magic Links and Email Codes
Module D: Social Sign-In
- Part 9: Sign In with GitHub
- Part 10: Account Linking and OAuth Access Tokens
Module E: Stronger Sign-In
- Part 11: Two-Factor Authentication (2FA)
- Part 12: Passkeys
- Part 13: Rate Limits, Captcha and Breached Passwords
Module F: Roles and Organizations
- Part 14: Admin Plugin: Roles, Bans and Impersonation
- Part 15: Custom Roles and Permissions
- Part 16: Organizations and Teams
Module G: Customize
- Part 17: Hooks, Database Hooks and the Server API
- Part 18: Database Adapters and Secondary Storage
- Part 19: Write Your Own Better Auth Plugin
Module H: APIs and Identity Provider
- Part 20: API Keys
- Part 21: JWT, Bearer and One-Time Tokens
- Part 22: Be an OAuth 2.1 and OpenID Connect Provider
- Part 23: MCP Servers and CLI Sign-In
Module I: Enterprise and Payments
- Part 24: Single Sign-On with OIDC and SAML
- Part 25: Subscriptions with Stripe
Module J: Ship It
- Part 26: Test Your Authentication
- Part 27: Production Security Checklist
- Part 28: Deploy to Vercel with a Free Neon Database
- Part 29: Migrate from Auth.js (NextAuth) to Better Auth
- Part 30: Final Project, Cheat Sheet and What to Learn Next
Cost: free. Everything in this part runs on your own computer.
Every command and output on this page is real, run on Better Auth 1.7 with Next.js 16.
Get the Source Code
Get the complete source code of Next.js Authentication with Better Auth and PostgreSQL on Dewiride Store → (opens in a new tab)
It’s a finished, tested version of this part’s Bookshop app, with a settings check, tests and a README.
Prerequisites
- the Bookshop project from Part 2: a Next.js app with Better Auth, its database tables in PostgreSQL and the route handler. Part 2 takes you there from an empty folder.
Where Your Project Is Now
Your project is the Bookshop from Part 2, with one change: a home page that lists the Bookshop’s books, so there’s something to see once people sign in. Replace everything in app/page.tsx with this file:
const books = [
{ title: "The Paper Lantern Café", author: "Mira Kale", price: 14.99 },
{ title: "A Map of Quiet Places", author: "Tomas Vell", price: 22.5 },
{ title: "The Clockmaker's Garden", author: "Mira Kale", price: 18 },
{ title: "Salt and Starlight", author: "Nadia Quill", price: 9.99 },
];
export default function Home() {
return (
<main className="mx-auto w-full max-w-3xl flex-1 px-6 py-12">
<h1 className="text-3xl font-semibold">Books</h1>
<ul className="mt-8 grid gap-4 sm:grid-cols-2">
{books.map((book) => (
<li
key={book.title}
className="rounded-lg border border-zinc-200 p-5 dark:border-zinc-800"
>
<p className="font-medium">{book.title}</p>
<p className="text-sm text-zinc-600 dark:text-zinc-400">
{book.author}
</p>
<p className="mt-3 font-semibold">${book.price.toFixed(2)}</p>
</li>
))}
</ul>
</main>
);
}
It’s plain React, a list of four books, with nothing about sign-in yet.
Step 1: Start the Database and the App
Open Terminal (PowerShell on Windows) in the bookshop folder. Start the PostgreSQL database from Part 2:
docker compose up -d
[+] up 1/1
✔ Container better-auth-bookshop-db-1 Started 0.3s
Then start the app:
npm run dev
npm notice run bookshop@0.1.0 dev
npm notice run next dev
▲ Next.js 16.4.6 (Turbopack)
- Local: http://localhost:3000
- Network: http://192.168.x.x:3000
- Environments: .env
✓ Ready in 334ms
✓ Running next.config.ts took 69ms
- Cache Components enabled
- Partial Prefetching enabled
Leave it running while you work: Next.js picks up every file you save. Open http://localhost:3000 in your browser:

Step 2: Turn On Email and Password Sign-In
Better Auth only allows the ways of signing in that you switch on. Open lib/auth.ts and add the emailAndPassword option after database:
emailAndPassword: {
enabled: true,
},
emailAndPasswordis Better Auth’s built-in email and password sign-in.enabled: trueswitches it on. Without it, Better Auth refuses to sign anyone up or in with a password.
The complete file:
import { betterAuth } from "better-auth";
import { Pool } from "pg";
export const auth = betterAuth({
database: new Pool({
connectionString: process.env.DATABASE_URL,
}),
emailAndPassword: {
enabled: true,
},
});
Better Auth never stores a password as typed: it hashes it with scrypt and keeps only the hash, in the account table. The tables from Part 2 already have room for it, so there’s nothing to migrate.
Step 3: Show Who’s Signed In
Every page gets a header that shows who’s signed in. Create a folder named components in the bookshop folder, and in it a file named user-menu.tsx:
"use client";
import Link from "next/link";
import { authClient } from "@/lib/auth-client";
export function UserMenu() {
const { data: session, isPending } = authClient.useSession();
if (isPending) {
return null;
}
if (!session) {
return (
<nav className="flex gap-4 text-sm">
<Link href="/sign-in">Sign in</Link>
<Link href="/sign-up">Sign up</Link>
</nav>
);
}
return (
<div className="flex items-center gap-4 text-sm">
<span>Signed in as {session.user.name}</span>
<button
type="button"
onClick={() => authClient.signOut()}
className="rounded border border-zinc-300 px-3 py-1 dark:border-zinc-700"
>
Sign out
</button>
</div>
);
}
"use client"makes this a client component: it runs in the browser, where the auth client from Part 2 works.authClient.useSession()returns the current session, and updates by itself when someone signs in or out.isPendingistruewhile it’s still asking Better Auth, so the menu shows nothing until it knows.- With no session, the menu shows links to the sign-in and sign-up pages. With one, it shows
session.user.name. authClient.signOut()ends the session. The header switches back to the links on its own.
Now put the menu on every page. Open app/layout.tsx and replace it with this file. The new parts are the two imports, the <header>, and the title and description:
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import Link from "next/link";
import { UserMenu } from "@/components/user-menu";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Bookshop",
description: "A bookshop with sign-in by Better Auth.",
};
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">
<header className="flex items-center justify-between border-b border-zinc-200 px-6 py-4 dark:border-zinc-800">
<Link href="/" className="font-semibold">
Bookshop
</Link>
<UserMenu />
</header>
{children}
</body>
</html>
);
}
Save both files. The home page now has the header, with links to pages you’ll create next:

Advertisement
Step 4: Add the Sign-Up Page
The sign-up page sends a name, an email address and a password to Better Auth. This is the part that does it:
const { error } = await authClient.signUp.email({
name: String(form.get("name")),
email: String(form.get("email")),
password: String(form.get("password")),
});
authClient.signUp.emailasks Better Auth to create the user.- When it fails,
error.messagesays why, and the page shows that message. - When it works, Better Auth has already signed the new user in, so
router.push("/")takes them to the home page.
In the app folder, create a folder named sign-up, and in it a file named page.tsx:
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { type FormEvent, useState } from "react";
import { authClient } from "@/lib/auth-client";
export default function SignUpPage() {
const router = useRouter();
const [errorMessage, setErrorMessage] = useState("");
const [isPending, setIsPending] = useState(false);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = new FormData(event.currentTarget);
setErrorMessage("");
setIsPending(true);
const { error } = await authClient.signUp.email({
name: String(form.get("name")),
email: String(form.get("email")),
password: String(form.get("password")),
});
setIsPending(false);
if (error) {
setErrorMessage(error.message ?? "Sign-up failed. Please try again.");
return;
}
router.push("/");
}
return (
<main className="mx-auto w-full max-w-sm flex-1 px-6 py-12">
<h1 className="text-2xl font-semibold">Create your account</h1>
<form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
<label className="flex flex-col gap-1 text-sm">
Name
<input
name="name"
required
autoComplete="name"
className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
/>
</label>
<label className="flex flex-col gap-1 text-sm">
Email
<input
name="email"
type="email"
required
autoComplete="email"
className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
/>
</label>
<label className="flex flex-col gap-1 text-sm">
Password
<input
name="password"
type="password"
required
minLength={8}
autoComplete="new-password"
className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
/>
</label>
{errorMessage && (
<p role="alert" className="text-sm text-red-600">
{errorMessage}
</p>
)}
<button
type="submit"
disabled={isPending}
className="rounded bg-zinc-900 px-4 py-2 text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900"
>
{isPending ? "Creating account…" : "Sign up"}
</button>
</form>
<p className="mt-6 text-sm">
Already have an account?{" "}
<Link href="/sign-in" className="underline">
Sign in
</Link>
</p>
</main>
);
}
minLength={8} on the password field matches Better Auth’s own minimum of 8 characters, so the browser points out a short password before it’s sent.
Open http://localhost:3000/sign-up and create Lena’s account: the name Lena Park, the email address lena@example.com and a password of at least 8 characters:

Click Sign up. The home page opens, and the header shows that Lena is signed in:

Better Auth keeps her signed in with a cookie named better-auth.session_token. It’s HttpOnly, so scripts in the page can’t read it, and it lasts 7 days.
Step 5: Add the Sign-In Page
Signing in works the same way, with an email address and a password:
const { error } = await authClient.signIn.email({
email: String(form.get("email")),
password: String(form.get("password")),
});
authClient.signIn.email checks the password and, when it’s right, starts a session. In the app folder, create a folder named sign-in, and in it a file named page.tsx:
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { type FormEvent, useState } from "react";
import { authClient } from "@/lib/auth-client";
export default function SignInPage() {
const router = useRouter();
const [errorMessage, setErrorMessage] = useState("");
const [isPending, setIsPending] = useState(false);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = new FormData(event.currentTarget);
setErrorMessage("");
setIsPending(true);
const { error } = await authClient.signIn.email({
email: String(form.get("email")),
password: String(form.get("password")),
});
setIsPending(false);
if (error) {
setErrorMessage(error.message ?? "Sign-in failed. Please try again.");
return;
}
router.push("/");
}
return (
<main className="mx-auto w-full max-w-sm flex-1 px-6 py-12">
<h1 className="text-2xl font-semibold">Sign in</h1>
<form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
<label className="flex flex-col gap-1 text-sm">
Email
<input
name="email"
type="email"
required
autoComplete="email"
className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
/>
</label>
<label className="flex flex-col gap-1 text-sm">
Password
<input
name="password"
type="password"
required
autoComplete="current-password"
className="rounded border border-zinc-300 px-3 py-2 dark:border-zinc-700"
/>
</label>
{errorMessage && (
<p role="alert" className="text-sm text-red-600">
{errorMessage}
</p>
)}
<button
type="submit"
disabled={isPending}
className="rounded bg-zinc-900 px-4 py-2 text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900"
>
{isPending ? "Signing in…" : "Sign in"}
</button>
</form>
<p className="mt-6 text-sm">
New to the Bookshop?{" "}
<Link href="/sign-up" className="underline">
Create an account
</Link>
</p>
</main>
);
}
autoComplete="current-password" lets the browser’s password manager fill in a saved password, where the sign-up page used new-password.
Try it. Click Sign out in the header. The links come back:

Open http://localhost:3000/sign-in, enter lena@example.com with a wrong password, and click Sign in:

The message doesn’t say which of the two was wrong. Enter Lena’s real password and click Sign in again: the home page opens, and the header shows Signed in as Lena Park.
Your project now has these new and changed files:
bookshop/
├── app/
│ ├── layout.tsx (changed)
│ ├── page.tsx (changed)
│ ├── sign-in/
│ │ └── page.tsx
│ └── sign-up/
│ └── page.tsx
├── components/
│ └── user-menu.tsx
└── lib/
└── auth.ts (changed)
Clean Up When You’re Done
Part 4 carries on with this project and Lena’s account, so keep both. To stop for now:
- In the Terminal where
npm run devruns, press Ctrl+C to stop the app. - Stop the database and keep its data with
docker compose stop. Next time,docker compose up -dstarts it again.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out "use client" at the top of a page or the menu | Next.js stops with an error, because hooks such as useState only work in client components | Keep "use client" as the first line of each of these files |
Forgetting enabled: true in lib/auth.ts | Better Auth refuses every sign-up and sign-in with a password | Add the emailAndPassword option from Step 2 |
Giving the form a different minLength from Better Auth’s minimum | The browser accepts a password that Better Auth then rejects | Keep minLength={8}, or change both together |
Troubleshooting
| Message | Cause | Fix |
|---|---|---|
User already exists. Use another email. | That email address already has an account | Sign in instead, or sign up with another email address |
Invalid email or password | The password, or the email address, is wrong | Check both and try again |
Password too short | The password has fewer than 8 characters, Better Auth’s minimum | Use a longer password |
FAQ
Where is Lena’s password stored?
In the account table, as a scrypt hash in the password column, never as she typed it. Better Auth Database Tables Explained shows every column.
Why is a new user signed in straight away?
Better Auth’s autoSignIn option is true by default. Set autoSignIn: false inside emailAndPassword if new users should sign in themselves.
How long does a session last?
7 days by default, and Better Auth extends it while the person keeps using the site. Part 5 covers session settings.
Can I stop new sign-ups?
Yes. disableSignUp: true inside emailAndPassword turns off sign-up with a password, while existing users can still sign in.
Conclusion
The Bookshop now has accounts. People sign up and sign in with an email address and a password, see who they’re signed in as, and sign out. Better Auth hashed Lena’s password, started her session and keeps her signed in with an HttpOnly cookie. Next, the server uses that session to decide who may see what.
← Previous: Part 2: Set Up Better Auth in Next.js with PostgreSQL
Coming next: Part 4: Protect Pages, Server Actions and API Routes.
Additional Resources
- Email & Password (opens in a new tab) in the Better Auth documentation
- Basic usage (opens in a new tab): signing up, signing in, signing out and
useSession - Client (opens in a new tab): the auth client and its errors
- Session management (opens in a new tab)
- Cookies (opens in a new tab)
- Server and Client Components (opens in a new tab) in the Next.js documentation
- useRouter (opens in a new tab) and Link (opens in a new tab) in Next.js
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