Adding Sign-In with an Auth Library
Lesson 2: Adding Sign-In with an Auth Library
How does a library fit into Next.js?
Most auth libraries follow the same shape:
| Piece | File | Role |
|---|---|---|
| Server config | lib/auth.ts |
Database, providers, session settings |
| API route | app/api/auth/[...all]/route.ts |
Handles sign-in, sign-out, callbacks |
| Client helper | lib/auth-client.ts |
Sign-in and sign-up calls from forms |
| Session reader | Used in Server Components and actions | Returns the current user or null |
Example (Better Auth)
// lib/auth.ts
import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
import { nextCookies } from 'better-auth/next-js';
import { db } from '@/lib/db';
export const auth = betterAuth({
database: prismaAdapter(db, { provider: 'postgresql' }),
emailAndPassword: { enabled: true },
plugins: [nextCookies()], // Lets Server Actions set auth cookies
});// app/api/auth/[...all]/route.ts
import { auth } from '@/lib/auth';
import { toNextJsHandler } from 'better-auth/next-js';
export const { GET, POST } = toNextJsHandler(auth);// lib/auth-client.ts
import { createAuthClient } from 'better-auth/react';
export const authClient = createAuthClient();// app/login/LoginForm.tsx
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { authClient } from '@/lib/auth-client';
export function LoginForm() {
const router = useRouter();
const [error, setError] = useState('');
async function onSubmit(formData: FormData) {
const { error } = await authClient.signIn.email({
email: String(formData.get('email')),
password: String(formData.get('password')),
});
if (error) return setError('Incorrect email or password.');
router.push('/dashboard');
router.refresh();
}
return (
<form action={onSubmit}>
<input name="email" type="email" required />
<input name="password" type="password" required />
<button>Sign in</button>
{error && <p role="alert">{error}</p>}
</form>
);
}Reading the session on the server:
// app/dashboard/page.tsx
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { auth } from '@/lib/auth';
export default async function Dashboard() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect('/login');
return <h1>Welcome back, {session.user.name}</h1>;
}> Note: Auth libraries such as Better Auth update their APIs often, so function names, imports, and setup steps may differ from the code above. Always follow the library's official Next.js guide for the version you install.
How it works
- The form calls the library's client, which posts to
/api/auth/.... - The library checks the password hash, creates a session, and sets a secure cookie.
- Server Components read the cookie through
headers()and get the session. - Reading the session makes the component request-time, so wrap it in Suspense on pages with a static shell (Module 7).
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Reading the session in the root layout | Every page becomes dynamic | Read it in components that need it, inside Suspense |
Forgetting router.refresh() after client sign-in |
Server Components show the signed-out state | Refresh or redirect from the server |
Committing BETTER_AUTH_SECRET or OAuth secrets |
Account takeover risk | Keep secrets in .env.local and the host's settings |
Key takeaways
- An auth library provides config, an API route, a client, and a session reader.
- Read the session on the server, and redirect when it is missing.
Try it: Add email and password sign-in to LearnHub and show the signed-in user's name on the dashboard.
Nextjs Tutorial
Jebasta








