Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 72 ยท Projects

Project: Login and Protected Pages

Build a complete login system in Next.js: database sessions, a secure cookie, a proxy guard, a data access layer and an admin-only page, with runnable stand-ins.

In this project you build the part of an app that every product eventually needs: people sign in, see pages that belong to them, and only administrators can open the admin area. You will use database sessions with a secure cookie, a small data access layer that every protected page calls, a proxy that redirects visitors without a cookie, and role checks that live next to the data they protect.

The earlier lessons explained the ideas one by one: Authentication and Sessions, Middleware and the Proxy File, Authorization and Data Security and Cookies and Headers. Here they come together in one small application, and the order matters: the guard that counts is the one that sits closest to the data.

Next.js cannot run on this site, so the Next.js files are read-only code blocks. The two runnable examples use node:crypto and plain functions to run the real logic: password checks, session creation and revocation, the proxy decision and the page-level checks. Each lesson part tells you which is which.

What you are building

Four screens

/login Email and password form.
/dashboard Any signed-in user.
/admin Admins only.
Log out Ends the session on the server.

A public home page sits outside all of it.

1 / 2

The folder layout:

TEXT
app/
  layout.tsx
  page.tsx                 public home page
  login/
    page.tsx
    login-form.tsx         client component (useActionState)
    actions.ts             login and logout Server Actions
  dashboard/page.tsx
  admin/page.tsx
lib/
  session.ts               create, read, delete sessions
  dal.ts                   verifySession, requireRole
  users.ts                 find user, verify password
proxy.ts

Step 1: sessions in the database

The cookie will hold a long random token and nothing else. The database stores a hash of that token, so a leaked table cannot be replayed as cookies. Logging out deletes the row, which ends the session immediately.

TypeScript
// lib/session.ts
import 'server-only';
import { randomBytes, createHash } from 'node:crypto';
import { cookies } from 'next/headers';
import { db } from '@/lib/db';

const COOKIE = 'session';
const TTL_MS = 7 * 24 * 60 * 60 * 1000;

const digest = (token: string) => createHash('sha256').update(token).digest('hex');

export async function createSession(userId: string) {
  const token = randomBytes(32).toString('base64url');
  const expiresAt = new Date(Date.now() + TTL_MS);

  await db.session.create({
    data: { id: digest(token), userId, expiresAt },
  });

  (await cookies()).set(COOKIE, token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: '/',
    expires: expiresAt,
  });
}

export async function getSessionUser() {
  const token = (await cookies()).get(COOKIE)?.value;
  if (!token) return null;

  const row = await db.session.findUnique({
    where: { id: digest(token) },
    include: { user: { select: { id: true, name: true, role: true } } },
  });
  if (!row || row.expiresAt < new Date()) return null;
  return row.user;
}

export async function deleteSession() {
  const store = await cookies();
  const token = store.get(COOKIE)?.value;
  if (token) await db.session.deleteMany({ where: { id: digest(token) } });
  store.delete(COOKIE);
}

Notice that getSessionUser returns the user's current role from the database. If you demote an administrator, their very next request already reflects it, which a role copied into a signed token could not do. The cookie flags are the ones from Cookies and Headers: httpOnly hides it from scripts, secure keeps it off plain HTTP, and sameSite: 'lax' blocks it on most cross-site requests.

The following stand-in runs the same logic with a Map instead of a database. It checks passwords with scrypt, stores only token hashes, builds the Set-Cookie header, and shows logout and expiry.

Node.js A session engine: login, expiry, logout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both failures give the same message, so the form does not reveal which emails exist, and the dummy hash keeps the response time similar. The cookie header shows every flag, the table never contains the raw token, and a role change takes effect on the next read. Real code would use argon2 or bcrypt from a library, as discussed in Authentication and Sessions.

Step 2: the data access layer

Instead of calling getSessionUser in a dozen places, put the checks in one small module. Every protected page, Server Action and Route Handler calls it. React's cache function makes repeated calls in one request run the lookup once.

TypeScript
// lib/dal.ts
import 'server-only';
import { cache } from 'react';
import { redirect } from 'next/navigation';
import { getSessionUser } from '@/lib/session';

export const verifySession = cache(async () => {
  const user = await getSessionUser();
  if (!user) redirect('/login');
  return user;
});

export async function requireRole(role: 'admin') {
  const user = await verifySession();
  if (user.role !== role) redirect('/dashboard');
  return user;
}

Pages become short and hard to get wrong:

TSX
// app/dashboard/page.tsx
import { verifySession } from '@/lib/dal';

export default async function Dashboard() {
  const user = await verifySession();
  return <h1>Welcome back, {user.name}</h1>;
}
TSX
// app/admin/page.tsx
import { requireRole } from '@/lib/dal';
import { listAllUsers } from '@/lib/users';

export default async function AdminPage() {
  await requireRole('admin');
  const users = await listAllUsers();
  return (
    <ul>
      {users.map((u) => (
        <li key={u.id}>{u.name} ({u.role})</li>
      ))}
    </ul>
  );
}

Because the page asks for the role before it reads the user list, there is no way to see the list by skipping an earlier step. The same two functions guard every Server Action that changes data.

Step 3: login and logout actions

TypeScript
// app/login/actions.ts
'use server';

import { redirect } from 'next/navigation';
import { createSession, deleteSession } from '@/lib/session';
import { findUserByEmail, verifyPassword } from '@/lib/users';

export async function login(_prev: { error?: string } | undefined, formData: FormData) {
  const email = String(formData.get('email') ?? '').trim().toLowerCase();
  const password = String(formData.get('password') ?? '');
  const next = String(formData.get('next') ?? '');

  const user = await findUserByEmail(email);
  const valid = await verifyPassword(password, user?.passwordHash);
  if (!user || !valid) return { error: 'Invalid email or password.' };

  await createSession(user.id);
  redirect(next.startsWith('/') && !next.startsWith('//') ? next : '/dashboard');
}

export async function logout() {
  await deleteSession();
  redirect('/login');
}

The next field lets a visitor return to the page they wanted. It is only honored when it is a local path: a value like //evil.com or https://evil.com would turn your login into an open redirect. The form itself is a Client Component that calls the action with useActionState and shows the returned error (see Building Forms with Server Actions):

TSX
// app/login/login-form.tsx
'use client';

import { useActionState } from 'react';
import { login } from './actions';

export function LoginForm({ next }: { next: string }) {
  const [state, formAction, pending] = useActionState(login, undefined);
  return (
    <form action={formAction}>
      <input type="hidden" name="next" value={next} />
      <label>Email <input name="email" type="email" required autoComplete="username" /></label>
      <label>Password <input name="password" type="password" required autoComplete="current-password" /></label>
      {state?.error && <p role="alert">{state.error}</p>}
      <button disabled={pending}>{pending ? 'Signing in...' : 'Sign in'}</button>
    </form>
  );
}

Step 4: the proxy guard

The proxy gives visitors without a cookie a quick redirect, before any page code runs. It cannot look in the database, so it only checks that a cookie exists. That is why it is a convenience, not the security.

TypeScript
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const hasCookie = request.cookies.has('session');

  if (pathname.startsWith('/login')) {
    return hasCookie
      ? NextResponse.redirect(new URL('/dashboard', request.url))
      : NextResponse.next();
  }

  if (!hasCookie) {
    const url = new URL('/login', request.url);
    url.searchParams.set('next', pathname);
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/admin/:path*', '/login'],
};

In Next.js 15 and earlier the file is middleware.ts and the function is named middleware. The next example runs the same decisions in plain JavaScript and then runs the page-level check, so you can see what each layer catches. Request 5 carries a cookie that looks right but was never issued.

Node.js Proxy plus page checks, side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the fifth line. The forged cookie gets past the proxy, because the proxy only saw that a cookie exists. The page-level check then finds no matching session and redirects. If the page had trusted the proxy, a visitor with any made-up cookie would have walked in. Request 3 shows the role check: Bob is signed in but is sent back to the dashboard when he asks for /admin.

Protecting actions and data, not only pages

A page check protects the page. A Server Action is a separate public endpoint, so it needs its own check, even when the button that calls it only exists on a protected page:

TypeScript
// app/admin/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { requireRole } from '@/lib/dal';
import { setUserRole } from '@/lib/users';

export async function promote(formData: FormData) {
  await requireRole('admin');
  const userId = String(formData.get('userId'));
  await setUserRole(userId, 'admin');
  revalidatePath('/admin');
}

Hardening checklist

  • Rate-limit login attempts per IP and per email, so passwords cannot be guessed endlessly.
  • Create a new session on login and delete the old one, so an id planted earlier is worthless.
  • Delete expired rows with a scheduled job, and delete all of a user's sessions on a password change.
  • Add CSRF thinking: Server Actions only accept POST and compare the Origin header, and sameSite: 'lax' helps, but keep state-changing endpoints off GET.
  • Serve over HTTPS and set secure in production. Name the cookie __Host-session there for extra protection, which requires secure, path: '/' and no domain.
  • Never cache protected pages publicly. Reading cookies() already makes the route dynamic, as explained in Static vs Dynamic Rendering.

For a production app you may prefer a library, which handles OAuth, password resets and email verification for you: see Auth.js, Better Auth and Clerk. Building it once by hand, as you just did, makes those libraries much easier to judge.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the database store a hash of the session token instead of the token itself?

    The cookie holds the raw random token. If someone steals only the database, the hashes are useless as cookies, because hashing cannot be reversed.
  2. 2. The proxy sees a cookie named session on a request to /admin. What does that prove?

    The proxy does not look in the database. A forged or expired cookie passes the same check, so the page or action must verify the session itself.
  3. 3. Where should the admin role check for a delete-user Server Action live?

    A Server Action is a public endpoint that can be called without the page. It must check the session and role itself.
  4. 4. Why is the next parameter only accepted when it starts with a single slash?

    A value such as //evil.com or https://evil.com would send a freshly signed-in user to an attacker's site. Only local paths are safe.
  5. 5. What is the advantage of reading the role from the database on every request?

    A role copied into a signed token stays valid until the token expires. A lookup always sees the current value.

Summary

  • The cookie holds a random token. The database stores its hash, the user id and an expiry, and deleting the row logs the user out at once.
  • Use one data access layer (verifySession, requireRole) that every page, action and handler calls. Wrap it in React's cache to look up once per request.
  • The proxy only checks that a cookie exists. It gives a fast redirect, but it is not security.
  • Check roles before reading protected data, and check again inside every Server Action.
  • Return one error for wrong email and wrong password, accept only local next paths, rate-limit logins and set httpOnly, secure and sameSite.

Next: Exercises with Solutions