Authentication concepts and sessions

Intermediate · 12 min

Separate authentication, sessions, and authorization, then build a cookie session in Next.js 16 with signed JWTs, the cookies API, and the right cookie flags.

Before thisDynamic APIs: cookies, headers, and searchParamsServer Actions basics

leerob · 12 min

Authentication concepts and sessions

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by leerobReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Auth is three separate jobs: authentication (prove who you are), session management (remember that across requests), and authorization (decide what you may see or do).
  • HTTP is stateless, so after login the server hands the browser something to send back each time: a cookie holding either the session data (stateless) or a session ID that points to a database row.
  • Set the session cookie on the server with `httpOnly`, `secure`, `sameSite`, an expiry, and a `path`; `cookies()` is async in Next.js 16, so you `await` it.
  • A signed JWT cannot be altered without the secret, but its payload is only encoded, not hidden, so keep the minimum data in it, such as a user id and role.
  • Hash passwords before storing them, validate form input on the server, and for anything beyond learning, the docs recommend an auth library over rolling your own.

Three jobs, one word

“Auth” gets used for several different things. The Next.js docs separate them, and so should you, because each fails in its own way.

  1. Authentication verifies the user is who they say they are, by having them prove it with something they have, such as a password.
  2. Session management tracks that state across requests.
  3. Authorization decides which routes and data they can reach.

This lesson covers the first two. Protecting routes and data covers the third.

Why a session exists at all

HTTP has no memory. Each request arrives with no idea whether the same person made the last one. If login only happened once and nothing carried forward, you would have to send the password every time.

So after a successful login the server hands the browser a token, and the browser sends it back on every request. A cookie is the standard carrier because browsers attach cookies to requests automatically. Think of it as a wristband at a venue: the door checks your ID once, and after that the wristband is the proof.

The docs describe two ways to fill the wristband.

  • Stateless sessions. The session data, or a token containing it, goes in the cookie. Each request is verified on the server by checking the token. Simpler, but the docs warn it can be less secure if not implemented correctly.
  • Database sessions. The data lives in a database row. The browser holds only an encrypted session ID. More secure and gives you control, such as tracking last login, counting active devices, or logging a user out everywhere, but more complex and heavier on the server.

You can use either, or both.

Authentication first: credentials in, user out

The docs’ example uses a form, a Server Action, and useActionState. The pieces from earlier lessons (forms and pending states, validation and error handling in actions) carry over directly. The steps in the action:

  1. Validate the fields on the server, with a schema library such as Zod, and return early when they fail.
  2. For signup, hash the password before it goes anywhere near the database. The docs use bcrypt.hash(password, 10).
  3. Insert the user, or look them up and check credentials.
  4. Create a session.
  5. Redirect.

The docs call their example verbose on purpose, to teach the steps, and say it shows how quickly a custom solution becomes complex. They recommend an auth library for increased security and simplicity. We cover those in Auth.js and auth libraries.

A stateless session, step by step

First, a secret key to sign with, kept in an environment variable:

openssl rand -base64 32
# .env
SESSION_SECRET=your_secret_key

Then functions to sign and verify. The docs use the jose library, and the server-only package so this code can never be imported into the browser bundle (see environment variables and server-only code):

// app/lib/session.ts
import 'server-only'
import { SignJWT, jwtVerify } from 'jose'
import { SessionPayload } from '@/app/lib/definitions'

const secretKey = process.env.SESSION_SECRET
const encodedKey = new TextEncoder().encode(secretKey)

export async function encrypt(payload: SessionPayload) {
  return new SignJWT(payload)
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('7d')
    .sign(encodedKey)
}

export async function decrypt(session: string | undefined = '') {
  try {
    const { payload } = await jwtVerify(session, encodedKey, {
      algorithms: ['HS256'],
    })
    return payload
  } catch (error) {
    console.log('Failed to verify session')
  }
}

Read the code, not the function name. encrypt calls SignJWT with HS256, which signs. A signed JWT is tamper-evident: change one character of the payload and verification fails. It is not secret: the payload is only encoded, so anyone holding the cookie can read it. That is why the docs say to put in the minimum unique data used on later requests, like a user id or role, and never personal data such as a phone number, email address, or card details, or a password.

import 'server-only'
import { cookies } from 'next/headers'

export async function createSession(userId: string) {
  const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
  const session = await encrypt({ userId, expiresAt })
  const cookieStore = await cookies()

  cookieStore.set('session', session, {
    httpOnly: true,
    secure: true,
    expires: expiresAt,
    sameSite: 'lax',
    path: '/',
  })
}

Each option does a job, per the docs:

  • httpOnly stops client-side JavaScript from reading the cookie, so a script injected into your page cannot steal it.
  • secure sends it only over HTTPS.
  • sameSite controls whether it is sent on cross-site requests.
  • expires (or Max-Age) removes it after a time.
  • path sets which URLs get it.

Set cookies on the server, to prevent client-side tampering. Note await cookies(); the dynamic APIs lesson explains why that call is async and what it does to rendering.

The Server Action then calls createSession(user.id) and redirect('/profile').

Refreshing and deleting

To keep a returning user signed in, re-set the cookie with a new expiry after verifying the current one. Logging out is a delete:

export async function deleteSession() {
  const cookieStore = await cookies()
  cookieStore.delete('session')
}

Call it from a logout action and redirect to /login.

The database version

For a database session, insert a row with the user id and expiry, take the returned ID, encrypt that into the cookie, and set the cookie with the same options. The docs note that keeping the cookie and the database in sync is optional but recommended, because it allows optimistic checks in the proxy without a database call. The cookie gets you a fast “probably logged in”; the row is the truth.

With Cache Components on

If you use Cache Components, the session read happens at request time, so it cannot be prerendered into the static shell. The docs have a separate guide: the component reading the session sits inside a <Suspense> boundary and streams in, and use cache cannot call cookies() directly. That guide’s example uses iron-session for encrypted cookie sessions, and the patterns apply to any session library. Reading cookies() outside a boundary is a build error with Cache Components.

What the video covers

Lee Robinson’s video is from February 2024, about eleven and a half minutes, and the Next.js authentication guide links to it. Per its title and the notes recorded when it was sourced, it builds cookie sessions by hand, with a JWT, then moves to Auth.js. We could not read a transcript, so we cannot say how it describes the JWT (the sourcing notes call it encrypted; the docs’ code signs). It predates Next.js 15 and 16: it uses middleware.ts, now proxy.ts, and calls cookies() synchronously, which is now async. Treat the code in this lesson as current and the video as the explanation of the flow. Delba’s 2024 talk, the runner-up, covers sessions, authorization, a data access layer, and DTOs with Next.js 14 APIs.

Where this fits

A session tells you who is asking. It does not stop anyone from asking for something they should not have. Next: protecting routes and data.

Check yourself

  1. 01What are the three concepts the Next.js docs split authentication into, and what does each answer?

    Authentication answers 'who is this?' by verifying credentials. Session management answers 'is this the same person as a moment ago?' by tracking auth state across requests. Authorization answers 'what may they access?' by deciding which routes and data are allowed.

  2. 02What is the difference between a stateless session and a database session?

    A stateless session stores the session data itself, or a token, in a cookie that is verified on each request. It is simpler but less secure if done badly. A database session stores the data in a table and gives the browser only an encrypted session ID, which is more secure and gives you control such as logging out all devices, at the cost of complexity and server resources.

  3. 03Why is the session cookie set in a Server Action rather than from client JavaScript?

    Cookies should be set on the server to prevent client-side tampering, and `httpOnly` stops client JavaScript from reading the cookie at all.

  4. 04A session payload is a signed JWT. Can the user read it?

    Yes. Signing prevents modification without the secret, but the payload is only encoded. That is why the docs say the payload should hold minimal, non-sensitive data like a user id and role, and never a password, email, or card details.

  5. 05Why do the docs mark `cookies()` with `await` in their examples?

    In current Next.js, `cookies()` is an async function, so you write `const cookieStore = await cookies()` before calling `set`, `get`, or `delete`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark