Proxy and Authentication · Lesson 21 of 24
Authentication in Next.js: Login and Sessions
Authentication answers "who is this user?" and authorisation "what may they do?". In Next.js the pieces are: a form that calls a Server Action, a signed session cookie, a data access layer that checks the session wherever data is read, and an optional Proxy redirect. This lesson builds a complete, working version so you understand what auth libraries do for you.
In this lesson
- Signed session cookies with jose
- Log in and log out with Server Actions
- A data access layer and protected pages
- Optimistic redirects in Proxy, and auth libraries
1. Sessions
# .env
SESSION_SECRET=generate-with-openssl-rand-base64-32-and-keep-secret
// lib/session.ts
import "server-only";
import { SignJWT, jwtVerify } from "jose";
import { cookies } from "next/headers";
const key = new TextEncoder().encode(process.env.SESSION_SECRET);
type Session = { userId: string; name: string };
export async function createSession(user: Session) {
const token = await new SignJWT(user)
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("7d")
.sign(key); // signed: can't be forged without the secret
(await cookies()).set("session", token, {
httpOnly: true, // JavaScript in the browser can't read it
secure: true, // HTTPS only (localhost is allowed)
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 7,
});
}
export async function readSession(token: string | undefined): Promise<Session | null> {
if (!token) return null;
try {
const { payload } = await jwtVerify(token, key, { algorithms: ["HS256"] });
return { userId: String(payload.userId), name: String(payload.name) };
} catch {
return null; // expired or tampered with
}
}
export async function deleteSession() {
(await cookies()).delete("session");
}
This is a stateless session: the signed cookie itself holds the user id. The alternative is a database session, where the cookie holds a random id that you look up – it lets you revoke sessions instantly.
2. Log in and log out
// app/actions.ts
"use server";
import { redirect } from "next/navigation";
import { z } from "zod";
import { createSession, deleteSession } from "@/lib/session";
const users = [{ id: "u1", email: "asha@example.com", name: "Asha", password: "react-is-fun" }]; // demo only!
const LoginSchema = z.object({ email: z.email(), password: z.string().min(8) });
export type LoginState = { error?: string; email?: string };
export async function login(prev: LoginState, formData: FormData): Promise<LoginState> {
const email = String(formData.get("email") ?? "");
const parsed = LoginSchema.safeParse(Object.fromEntries(formData));
if (!parsed.success) return { error: "Enter a valid email and password", email };
const user = users.find((u) => u.email === parsed.data.email);
// real apps store a hash and compare with bcrypt/argon2: await verify(user.passwordHash, password)
if (!user || user.password !== parsed.data.password) return { error: "Wrong email or password", email }; // keep the email
await createSession({ userId: user.id, name: user.name });
redirect("/dashboard");
}
export async function logout() {
await deleteSession();
redirect("/login");
}
// app/login/login-form.tsx
"use client";
import { useActionState } from "react";
import { login, type LoginState } from "../actions";
export function LoginForm() {
const [state, formAction, pending] = useActionState<LoginState, FormData>(login, {});
return (
<form action={formAction}>
<label>Email <input name="email" type="email" defaultValue={state.email} key={state.email} /></label>
<label>Password <input name="password" type="password" /></label>
<button disabled={pending}>Log in</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}
// app/login/page.tsx
import { LoginForm } from "./login-form";
export default function LoginPage() {
return (
<main>
<h1>Log in</h1>
<LoginForm />
</main>
);
}
3. A data access layer
Every read of private data goes through functions that check the session first – so a page, an action or an API route can't forget:
// lib/dal.ts
import "server-only";
import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { readSession } from "./session";
export const verifySession = cache(async () => {
const session = await readSession((await cookies()).get("session")?.value);
if (!session) redirect("/login");
return session;
});
export async function getMyProgress() {
const { userId } = await verifySession(); // authorisation lives next to the data
// return db.progress.findMany({ where: { userId } }) – only this user's rows
return userId === "u1" ? { completed: 12, total: 24 } : { completed: 0, total: 24 };
}
// app/dashboard/page.tsx
import { Suspense } from "react";
import { getMyProgress, verifySession } from "@/lib/dal";
import { logout } from "../actions";
async function Dashboard() {
const session = await verifySession();
const progress = await getMyProgress();
return (
<>
<h1>Welcome, {session.name}</h1>
<p>{progress.completed} of {progress.total} lessons complete</p>
<form action={logout}>
<button>Log out</button>
</form>
</>
);
}
export default function Page() {
return (
<Suspense fallback={<p>Loading…</p>}>
<Dashboard />
</Suspense>
);
}
4. An optimistic check in Proxy
Proxy can redirect obviously logged-out visitors before any page work happens. It only reads the cookie – no database:
// proxy.ts
import { NextResponse, type NextRequest } from "next/server";
import { readSession } from "@/lib/session";
export async function proxy(request: NextRequest) {
const session = await readSession(request.cookies.get("session")?.value);
const { pathname } = request.nextUrl;
if (pathname.startsWith("/dashboard") && !session) {
return NextResponse.redirect(new URL("/login", request.url));
}
if (pathname === "/login" && session) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return NextResponse.next();
}
export const config = { matcher: ["/dashboard/:path*", "/login"] };
URL: /login Log in Email [] Password [] [Log in] › type “asha@example.com” into Email URL: /login Log in Email [asha@example.com] Password [] [Log in] › type “wrong-password” into Password URL: /login Log in Email [asha@example.com] Password [••••••••••••••] [Log in] › click “Log in” URL: /login Log in Email [asha@example.com] Password [] [Log in] Wrong email or password › clear Password and type “react-is-fun” URL: /login Log in Email [asha@example.com] Password [••••••••••••] [Log in] Wrong email or password › click “Log in” URL: /dashboard Welcome, Asha 12 of 24 lessons complete [Log out] › open /login URL: /dashboard Welcome, Asha 12 of 24 lessons complete [Log out] › click “Log out” URL: /login Log in Email [] Password [] [Log in]
Step by step: the logged-out visit to /dashboard was redirected to /login by Proxy; a wrong password returned an error from the action (React resets a form after its action runs, so the action also returns the email and the field is refilled from it); the right one set the session cookie and redirected to the dashboard, where the data access layer read the session; visiting /login while logged in bounced back to the dashboard; and logging out deleted the cookie.
Production checklist
- Hash passwords with bcrypt or argon2 – never store or compare plain text like the demo.
- Check the session in the data layer, every Server Action and every Route Handler – not only in Proxy or layouts.
- Return only the fields the UI needs (no password hashes or internal ids in props).
- Rate-limit login attempts, and use HTTPS everywhere.
Auth libraries
In real projects you'll usually reach for a library that handles OAuth ("Log in with Google/GitHub"), email links, password resets and session rotation: Auth.js (NextAuth), Better Auth, or hosted services like Clerk, Auth0 and Supabase Auth. They follow the same model you've just built – a session, checked on the server close to the data.
Practice
Try it yourself
Protect a Route Handler:
GET /api/mereturns{ name }for a valid session cookie and 401 otherwise.Show solution
// app/api/me/route.ts import { cookies } from "next/headers"; import { readSession } from "@/lib/session"; export async function GET() { const session = await readSession((await cookies()).get("session")?.value); if (!session) return Response.json({ error: "Not logged in" }, { status: 401 }); return Response.json({ name: session.name }); }// lib/session.ts import "server-only"; import { jwtVerify } from "jose"; const key = new TextEncoder().encode(process.env.SESSION_SECRET); export async function readSession(token: string | undefined) { if (!token) return null; try { const { payload } = await jwtVerify(token, key, { algorithms: ["HS256"] }); return { name: String(payload.name) }; } catch { return null; } }# .env SESSION_SECRET=generate-with-openssl-rand-base64-32-and-keep-secretGET /api/me → 401 application/json {"error":"Not logged in"}
Quick check
Why make the session cookie httpOnly?
So browser JavaScript (including injected scripts) can't read it.
Where should authorisation checks live?
In a data access layer next to the data, and in every Server Action and Route Handler.
What can Proxy safely do for auth?
Optimistic redirects based on the cookie – not database lookups or final security decisions.
Summary
- Log in with a Server Action that validates input and creates a signed, httpOnly session cookie.
- A cached verifySession in a server-only data access layer protects every data read.
- Proxy adds fast optimistic redirects; libraries like Auth.js or Clerk handle OAuth and more.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.