Skip to main content
0 reactions

Better Auth Tutorial — Part 2: Set Up Better Auth in Next.js with PostgreSQL

A dark indigo card titled Set Up Better Auth, labelled Better Auth Tutorial Part 2, with the line In Next.js 16, with PostgreSQL 18 running in Docker, beside a terminal window with four ticked lines: create-next-app, postgres:18, npx auth migrate and /api/auth/ok.
Better Auth Tutorial, Part 2: Set Up Better Auth in Next.js with PostgreSQL.

In Part 1 you saw how Better Auth works. Now you’ll set it up for real: a Next.js app, a PostgreSQL database in Docker, and Better Auth connected to both. This Better Auth Next.js setup is the base every later part of the series builds on.

By the end of this part, you’ll have:

  • a Next.js 16 app called bookshop, the start of the bookshop website from Part 1
  • PostgreSQL 18 running in Docker on your own computer
  • Better Auth connected to that database, with its four tables created
  • Better Auth’s route answering in your browser at /api/auth/ok

This is Part 2 of the Better Auth Tutorial. The parts in Module A, Start Here:

All parts of the Better Auth Tutorial

Module A: Start Here

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 the finished, tested Bookshop app: this part’s setup plus the sign-up and sign-in pages from Part 3, ready to run.

Prerequisites

Every command in this part works the same in Terminal on macOS and Linux and in PowerShell on Windows.

Step 1: Create the Next.js App

Next.js comes with its own setup tool, create-next-app. Open Terminal (PowerShell on Windows) in the folder where you keep your projects, and run:

TerminalBash
npx create-next-app@latest bookshop --biome
  • npx runs a tool from npm without installing it first.
  • create-next-app@latest is the newest version of Next.js’s setup tool.
  • bookshop is the name of the new project and of its folder.
  • --biome sets up Biome to check your code. ESLint, the other choice, can’t yet check code with TypeScript 7, which Step 2 installs.

Because you gave an option, create-next-app uses its recommended settings for everything else and asks no questions. The first time, npx asks Ok to proceed? (y): type y and press Return.

The output lists the settings it chose, such as TypeScript, Tailwind CSS and the App Router, then installs the packages (the folder paths are shortened here):

OutputPlain text
npm notice run npx
npm notice run 'create-next-app' bookshop --biome

Using defaults for unprovided options:

  --ts                    TypeScript (use --js for JavaScript)
  --no-react-compiler     No React Compiler (use --react-compiler for React Compiler)
  --tailwind              Tailwind CSS (use --no-tailwind for No Tailwind CSS)
  --no-src-dir            No src/ directory (use --src-dir for src/ directory)
  --app                   App Router (use --no-app for Pages Router)
  --cache-components      Cache Components (use --no-cache-components for No Cache Components)
  --agents-md             AGENTS.md (use --no-agents-md for No AGENTS.md)
  --no-agent-feedback     No agent feedback (use --agent-feedback for Agent feedback)
  --import-alias          "@/*"

Creating a new Next.js app in …/bookshop.

Using npm.

Initializing project with template: app-tw


Installing dependencies:
- next
- react
- react-dom

Installing devDependencies:
- @biomejs/biome
- @tailwindcss/turbopack
- @types/node
- @types/react
- @types/react-dom
- tailwindcss
- typescript


added 48 packages, and audited 49 packages in 5s

11 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

npm notice run bookshop@0.1.0 npx
npm notice run 'next' typegen
Generating route types...
✓ Types generated successfully

Initialized a git repository.

Success! Created bookshop at …/bookshop

Move into the new folder. Run every command in the rest of this part from inside it:

TerminalBash
cd bookshop

Step 2: Update the Packages to the Newest Versions

create-next-app installs some packages at older versions: React 19.3.0, Tailwind CSS 4.3.3, Biome 2.4.2, TypeScript 5 and the types for Node.js 20. This series uses the newest releases, so update them now.

First React, the library Next.js builds its pages with:

TerminalBash
npm install react@latest react-dom@latest
OutputPlain text
changed 2 packages, and audited 49 packages in 2s

11 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Then the tools you only need while you build the app. --save-dev records them as development dependencies:

TerminalBash
npm install --save-dev typescript@latest @types/node@latest @biomejs/biome@latest tailwindcss@latest @tailwindcss/turbopack@latest
OutputPlain text
added 3 packages, changed 13 packages, and audited 58 packages in 6s

12 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Biome’s settings file, biome.json, was written for the older Biome. This command updates it:

TerminalBash
npx biome migrate --write
OutputPlain text
npm notice run bookshop@0.1.0 npx
npm notice run 'biome' migrate --write
configuration ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  i Migration results:

  - …/bookshop/biome.json: configuration successfully migrated.

Step 3: Install Better Auth

Install Better Auth and pg, the PostgreSQL driver Better Auth uses to talk to the database:

TerminalBash
npm install better-auth pg
OutputPlain text
added 35 packages, removed 1 package, and audited 92 packages in 11s

17 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

pg doesn’t include TypeScript types, so add them as a development dependency:

TerminalBash
npm install --save-dev @types/pg
OutputPlain text
added 1 package, and audited 93 packages in 2s

17 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Step 4: Start PostgreSQL in Docker

Better Auth keeps its users and sessions in a database. You’ll run PostgreSQL in Docker, so there’s nothing to install: Docker Compose starts it from a short settings file. Make sure Docker Desktop is running.

In your code editor, create a file named compose.yaml in the bookshop folder:

compose.yamlYAML
name: better-auth-bookshop

services:
  db:
    image: postgres:18
    environment:
      POSTGRES_USER: bookshop
      POSTGRES_PASSWORD: local-only-password
      POSTGRES_DB: bookshop
    ports:
      - "127.0.0.1:5435:5432"
    volumes:
      - db-data:/var/lib/postgresql

volumes:
  db-data:

What each part does:

  • name: better-auth-bookshop is the name Docker shows for this project, so it never mixes with another project called bookshop.
  • image: postgres:18 is the official PostgreSQL image at version 18, the newest release.
  • environment sets the user name, password and database PostgreSQL creates when it first starts. This password only protects the database on your own computer.
  • "127.0.0.1:5435:5432" makes the database reachable on port 5435, and only from your own computer. Port 5435 avoids a clash with a PostgreSQL already installed on your computer, which would use 5432.
  • db-data:/var/lib/postgresql keeps the database files in a Docker volume, so your data survives when the container is replaced. PostgreSQL 18 keeps its data in this folder.

Start the database:

TerminalBash
docker compose up -d

up starts everything in compose.yaml, and -d runs it in the background, so you get your Terminal back. The first time, Docker downloads the PostgreSQL image:

OutputPlain text
[+] up 17/17
 ✔ Image postgres:18                    Pulled                                       21.4s
 ✔ Volume better-auth-bookshop_db-data  Created                                       0.0s
 ✔ Network better-auth-bookshop_default Created                                       0.0s
 ✔ Container better-auth-bookshop-db-1  Started                                       0.8s

Step 5: Add the Secret and the Environment Variables

Better Auth needs a secret: a long random value it uses to encrypt and sign data, such as your users’ session cookies. Its command-line tool, the auth package, makes one for you:

TerminalBash
npx auth@latest secret

The first time, npx asks to install auth: type y. It then prints a new secret. Yours is a different 64-character value, so it’s hidden here:

OutputPlain text
Need to install the following packages:
auth@1.7.26
Ok to proceed? (y) y
npm notice run bookshop@0.1.0 npx
npm notice run 'auth' secret
Add the following to your .env file:
BETTER_AUTH_SECRET=<your-secret>

In your code editor, create a file named .env in the bookshop folder. Paste your BETTER_AUTH_SECRET line into it, and add the two lines below it:

.envPlain text
BETTER_AUTH_SECRET=<your-secret>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=postgres://bookshop:local-only-password@localhost:5435/bookshop
  • BETTER_AUTH_SECRET is your secret. Better Auth reads it from this name by itself.
  • BETTER_AUTH_URL is the address of your app. Better Auth reads it by itself too, and its documentation advises always setting it.
  • DATABASE_URL tells the app where the database is: user bookshop, its password, your own computer (localhost), port 5435 and the database bookshop, all from compose.yaml.

Warning: Keep .env private and out of Git. Better Auth signs and encrypts your users’ data with this secret. create-next-app’s .gitignore file already keeps every .env file out of Git.

Advertisement

Step 6: Create the Better Auth Instance

First, tell Node.js that this project’s files use import and export. Open package.json and add the "type" line under "private": true,:

package.json (excerpt)JSON
  "private": true,
  "type": "module",

Better Auth’s command-line tool loads your settings file with Node.js. Without this line, Node.js prints a MODULE_TYPELESS_PACKAGE_JSON warning every time you run it (why, and the fix).

Now create the file that sets up Better Auth. Make a folder named lib in the bookshop folder, and in it a file named auth.ts:

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

export const auth = betterAuth({
  database: new Pool({
    connectionString: process.env.DATABASE_URL,
  }),
});
  • betterAuth({ … }) creates Better Auth with your settings. The rest of the app imports it as auth.
  • database: new Pool({ … }) connects Better Auth to PostgreSQL through pg. A pool keeps a few connections open and reuses them.
  • process.env.DATABASE_URL reads the database address from .env.

The secret and the app’s address aren’t in this file: Better Auth finds BETTER_AUTH_SECRET and BETTER_AUTH_URL by itself.

Step 7: Create the Database Tables

Better Auth needs four tables in the database. Its command-line tool creates them from your settings:

TerminalBash
npx auth@latest migrate

It lists the tables and fields it will add and asks you to confirm. Type y and press Return:

OutputPlain text
npm notice run bookshop@0.1.0 npx
npm notice run 'auth' migrate
🔑 The migration will affect the following:
-> name, email, emailVerified, image, createdAt, updatedAt fields on user table.
-> expiresAt, token, createdAt, updatedAt, ipAddress, userAgent, userId fields on session table.
-> accountId, providerId, userId, accessToken, refreshToken, idToken, accessTokenExpiresAt, refreshTokenExpiresAt, scope, password, createdAt, updatedAt fields on account table.
-> identifier, value, expiresAt, createdAt, updatedAt fields on verification table.
✔ Are you sure you want to run these migrations? … yes
🚀 migration was completed successfully!
A Terminal window showing npx auth@latest migrate listing the fields it adds to the user, session, account and verification tables, the confirmation answered yes, and the message migration was completed successfully.
npx auth@latest migrate creates Better Auth’s four tables.

The database now has the user, session, account and verification tables that Part 1 described. When you add a plugin in a later part, you run this command again to add the plugin’s tables.

Step 8: Add the Route Handler

Better Auth answers every sign-in request under /api/auth. In Next.js, one route file hands those requests to it. In the app folder, create the folders api, then auth inside it, then [...all] inside that, with the square brackets and the three dots. In the last one, create a file named route.ts:

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

export const { POST, GET } = toNextJsHandler(auth);
  • [...all] is a catch-all folder name: the file answers /api/auth and every address below it, such as /api/auth/ok.
  • toNextJsHandler(auth) turns Better Auth into the GET and POST functions that Next.js calls for each request.

Step 9: Create the Auth Client

Your pages talk to Better Auth through its client. In the lib folder, create auth-client.ts:

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

export const authClient = createAuthClient();

createAuthClient comes from better-auth/react, the client for React and Next.js. It needs no address, because your pages and Better Auth run in the same app. Part 3 uses it to sign people up and in.

Step 10: Run the App and Test Better Auth

Start the app in development mode:

TerminalBash
npm run dev
OutputPlain text
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 282ms
✓ Running next.config.ts took 80ms
- Cache Components enabled
- Partial Prefetching enabled

Environments: .env shows that Next.js loaded your settings. Open http://localhost:3000 in your browser. Next.js’s start page shows that the app runs:

The Next.js start page in a browser, with the Next.js logo, the heading To get started, edit the page.tsx file, and the buttons Deploy Now and Documentation.
The new app’s start page at localhost:3000.

Now open http://localhost:3000/api/auth/ok. This time Better Auth answers, through your route handler:

A browser showing the reply from localhost:3000/api/auth/ok: the JSON text ok true.
Better Auth’s reply at /api/auth/ok.

{"ok":true} means the route handler, Better Auth and its settings work together. Nobody can sign in yet: http://localhost:3000/api/auth/get-session answers null, because there’s no session. Part 3 adds sign-up and sign-in.

Your project now has these new files, next to the ones create-next-app made:

Project filesPlain text
bookshop/
├── app/
│   └── api/
│       └── auth/
│           └── [...all]/
│               └── route.ts
├── lib/
│   ├── auth.ts
│   └── auth-client.ts
├── .env
├── compose.yaml
└── package.json

Clean Up When You’re Done

Part 3 carries on with this project, so keep the folder and the database. To stop for now:

  1. Stop the app: press Ctrl+C in the Terminal window where npm run dev runs.
  2. Stop the database: run docker compose stop in the bookshop folder. Your data stays, and docker compose start starts it again.

Warning: docker compose down -v removes the database container and deletes its volume, with every user and session in it. Use it only when you’re finished with the whole series.

More ways to stop, start and remove Docker Compose containers: How to Stop, Start and Remove Docker Compose Containers Without Losing Data (opens in a new tab).

Common Mistakes

MistakeWhat happensDo this instead
Running the commands outside the bookshop foldernpm and npx can’t find the projectRun cd bookshop first
Leaving out "type": "module"Every npx auth command prints a MODULE_TYPELESS_PACKAGE_JSON warningAdd the line to package.json (Step 6)
Putting .env in Git or sharing itYour secret and your database password leakKeep .env private. The .gitignore file already covers it.
Changing lib/auth.ts without migratingNew features can’t find their tablesRun npx auth@latest migrate again after adding a plugin

Troubleshooting

ProblemCauseFix
npx auth@latest migrate prints ECONNREFUSEDThe database isn’t runningStart Docker Desktop, then run docker compose up -d
npx asks Ok to proceed? (y)It’s the first time you run that toolType y and press Return
The MODULE_TYPELESS_PACKAGE_JSON warningpackage.json has no "type" lineAdd "type": "module" (Step 6)

FAQ

Do I need Docker?

No. Any PostgreSQL database works: put its address in DATABASE_URL. This series uses Docker because the same two commands work on every computer.

Can I use .env.local instead of .env?

Yes. Next.js and Better Auth’s command-line tool both read .env and .env.local.

What does npx auth@latest do?

It runs the newest version of auth, Better Auth’s command-line tool, without adding it to your project.

Why port 5435 instead of PostgreSQL’s usual 5432?

A PostgreSQL installed on your computer may already use 5432. Port 5435 keeps this database out of its way.

Why can’t I sign in yet?

This part sets up Better Auth. Part 3 switches on email and password sign-in and builds the sign-up and sign-in pages.

Conclusion

You set up Better Auth in a Next.js app: PostgreSQL runs in Docker, Better Auth has its four tables, and /api/auth answers in your browser. Every later part builds on this project.

← Previous: Part 1: What Is Better Auth?

Next → Part 3: Sign Up and Sign In with Email and Password: build the sign-up and sign-in pages, sign out, and show who’s signed in.

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