Full Stack 45:222025-09-15
Build Authentication in Next.js with Better Auth (The Right Way)
A complete walkthrough of setting up session-based authentication with Better Auth in a Next.js App Router project. Sessions, protected routes, OAuth — all covered.
Watch on YouTube
Click to open in YouTube
Video Notes & Code
Key takeaways, code snippets, and resources from this video.
Setup
bash
npm install better-authtypescript
// lib/auth.ts
import { betterAuth } from 'better-auth'
import { Pool } from 'pg'
export const auth = betterAuth({
database: new Pool({ connectionString: process.env.DATABASE_URL }),
emailAndPassword: { enabled: true },
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}
}
})Protecting Routes with Middleware
typescript
// middleware.ts
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
export async function middleware(req: NextRequest) {
const session = await auth.api.getSession({ headers: req.headers })
if (!session && req.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', req.url))
}
return NextResponse.next()
}Found this useful?
Subscribe for weekly content on AI engineering, SaaS building, and full stack development.