Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 72 ยท Middleware, Proxy and Auth

Authentication and Sessions

Build authentication in Next.js from first principles: password hashing, cookie sessions, signed tokens versus database sessions, a login flow and protected pages.

Authentication answers one question: who is making this request? HTTP has no memory, so after a visitor proves their identity once (usually with a password), your app needs a way to recognize them on every later request. The standard answer is a session: a small piece of data that the browser stores in a cookie and sends back each time.

Libraries can do most of this for you, and Auth.js, Better Auth and Clerk are covered later. But you should understand the moving parts first, because every library is built on the same ideas, and because the mistakes in this area are expensive. This lesson covers how passwords should be stored, the two main kinds of sessions, a complete login flow with Server Actions, and how to protect pages.

Next.js itself cannot run on this site, so the Next.js code is read-only. The runnable examples use node:crypto to build the real building blocks: a signed token, a revocable session store and password hashing. Those parts are not stand-ins, they are the actual primitives that libraries use.

The pieces of a login system

What a login needs

Password check Compare against a salted hash, never plain text.
Session A token that says who the visitor is.
Cookie Carries the token, httpOnly and secure.
Guard Every protected page checks the session.

Each piece can fail on its own, so build and test them separately.

1 / 2

Never store passwords as they are

When someone registers, you store a hash of the password, not the password. A hash is a one-way function: easy to compute, practically impossible to reverse. When they log in, you hash what they typed and compare. For passwords you need a deliberately slow hash with a random salt per user: argon2, scrypt or bcrypt. Fast hashes like plain SHA-256 let an attacker try billions of guesses per second after a leak. The salt makes two users with the same password produce different hashes.

Node.js ships scrypt in node:crypto, so the first example needs no package. Libraries such as argon2 or bcryptjs follow exactly the same shape.

Node.js Salted password hashing with scrypt

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.

The stored value contains the scheme, the salt and the hash, so a verify function has everything it needs. Two hashes of the same password differ because the salt differs, yet both verify. timingSafeEqual avoids leaking how many leading bytes matched through response time.

A stateless session stores the data itself in the cookie, protected by a signature. The server signs it with a secret key. On the next request it recomputes the signature: if it matches, the data was not changed. The best-known format is a JWT (JSON Web Token): header.payload.signature, each part Base64URL-encoded.

Two facts to keep in mind. The payload is encoded, not encrypted: anyone who has the cookie can read it, so never put secrets in it. And the signature check must be strict: reject unexpected algorithms (the infamous alg: none trick), compare in constant time, and check the expiry.

Node.js Sign and verify a token with HMAC

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.

The result shows why the signature matters. Changing role to admin produces a payload that no longer matches the signature, so verification fails. The same token stops working at its expiry time. Real code should use a maintained library for this, such as jose, which handles the edge cases for you. Keep the secret in an environment variable of at least 32 random bytes, and keep it out of Git.

Option 2: a database session

A database session stores almost nothing in the cookie: just a long random id, with no meaning of its own. The data (user id, expiry, device) lives in a table or in Redis. Each request looks the id up.

Here is the practical difference, which is also the most common reason people choose one or the other. With a signed token there is nothing to look up, so it is cheap and scales without a shared store, but the server cannot revoke one: the token is valid until it expires. With a database session, logging out or banning a user means deleting a row, and the next request fails immediately.

Node.js Logging out: token versus database session

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.

After logout the token still verifies, while the session is gone. Teams that want both benefits often combine them: a short-lived signed token (say 10 minutes) refreshed from a database record, or a signed cookie that contains a session id. Pick the database session when immediate revocation matters, which is most apps with accounts, payments or admin screens.

The login flow in Next.js

sequenceDiagram
  participant B as Browser
  participant A as Server Action
  participant D as Database
  B->>A: POST email + password
  A->>D: Find user by email
  D-->>A: User with password hash
  A->>A: Verify hash, create session
  A-->>B: Set-Cookie session (httpOnly) + redirect
  B->>A: Next request with the cookie
  A->>A: Read and verify session
  A-->>B: Page for this user

The cookie is set once, then travels with every request.

First a small module that creates and reads the session. It is marked server-only so it can never be imported into a Client Component (see Keeping Server Code on the Server). This version uses a signed token with the jose library:

TypeScript
// 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);
const WEEK = 7 * 24 * 60 * 60 * 1000;

export async function createSession(userId: string, role: 'user' | 'admin') {
  const expiresAt = new Date(Date.now() + WEEK);
  const token = await new SignJWT({ userId, role })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime(expiresAt)
    .sign(key);

  const cookieStore = await cookies();
  cookieStore.set('session', token, {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    expires: expiresAt,
    path: '/',
  });
}

export async function readSession() {
  const token = (await cookies()).get('session')?.value;
  if (!token) return null;
  try {
    const { payload } = await jwtVerify(token, key, { algorithms: ['HS256'] });
    return { userId: String(payload.userId), role: payload.role as 'user' | 'admin' };
  } catch {
    return null; // bad signature or expired
  }
}

export async function deleteSession() {
  (await cookies()).delete('session');
}

Then the login and logout actions. The login action returns an error message for failures and redirects on success (the form wiring is explained in Building Forms with Server 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(_previous: unknown, formData: FormData) {
  const email = String(formData.get('email') ?? '').trim().toLowerCase();
  const password = String(formData.get('password') ?? '');

  const user = await findUserByEmail(email);
  const valid = user ? await verifyPassword(password, user.passwordHash) : false;

  if (!user || !valid) {
    return { error: 'Invalid email or password.' }; // same message for both cases
  }

  await createSession(user.id, user.role);
  redirect('/dashboard'); // redirect() throws, so it must stay outside try/catch
}

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

Two details deserve attention. The error message is the same whether the email or the password was wrong, so the form does not reveal which emails have accounts. And redirect() works by throwing a special error, so never wrap it in a try/catch that swallows errors.

Protecting pages

The most basic guard reads the session in the page and redirects when it is missing:

TSX
// app/dashboard/page.tsx
import { redirect } from 'next/navigation';
import { readSession } from '@/lib/session';

export default async function Dashboard() {
  const session = await readSession();
  if (!session) redirect('/login');

  return <h1>Welcome back, user {session.userId}</h1>;
}

You can add a quick optimistic check in the proxy file, which redirects visitors without a session cookie before anything renders. That gives a fast, friendly experience, but it only looks at the cookie, so treat it as a convenience. The check that counts happens where the data is read, because pages, Server Actions and Route Handlers can all be reached directly. That idea gets its own lesson: Authorization and Data Security.

A session needs a few more habits to be safe. Set a reasonable expiry. Regenerate the session on login so an id planted before login is useless. Rate-limit login attempts. Offer logout that really ends the session. And never put the session in localStorage, where any script on the page can read it, while an httpOnly cookie is out of reach of scripts. Cookies and Headers explains the cookie options.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a password stored as a salted, slow hash?

    A one-way, deliberately slow hash with a per-user salt makes leaked data much harder to crack. You can never recover the password, which is the point.
  2. 2. What is true about the payload of a JWT?

    A signed JWT is encoded (Base64URL), not encrypted. The signature protects against changes, not against reading.
  3. 3. A user clicks 'log out everywhere'. Which session style stops working immediately?

    A database session is looked up on each request, so deleting the row ends it. A stateless token stays valid until it expires unless you add a server-side check.
  4. 4. Where should the session cookie be set from in Next.js?

    Only actions and handlers can write cookies, and httpOnly keeps scripts from reading the session.
  5. 5. Why should a login form show the same error for 'unknown email' and 'wrong password'?

    Different messages would let anyone test which email addresses are registered.

Summary

  • Authentication proves who someone is. A session lets the app remember it between requests, usually through a cookie.
  • Store passwords as slow, salted hashes (argon2, scrypt, bcrypt), and compare in constant time.
  • A signed token (JWT) needs no lookup but cannot be revoked before it expires. A database session needs a lookup but can be ended at once.
  • The cookie must be httpOnly, secure and sameSite. Set it from a Server Action or Route Handler, after validating the login.
  • Return the same error for unknown emails and wrong passwords, and do not wrap redirect() in try/catch.
  • A proxy check is a convenience. The real check belongs where data is read.

Next: Authorization and Data Security