Files
Joseph 8ff8f1b82e docs: add authentication with Cache Components guide and iron-session example (#95802)
- new guide, Auth w/ Cache Components
- iron-session example w/ Cache Components

TODO:

- [x] opt-out from the instant requirements
- [x] e2e for the example, using instant helper

---------

Co-authored-by: Aurora Scharff <66901228+aurorascharff@users.noreply.github.com>
Co-authored-by: Aurora Scharff <aurora.sofie@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 09:49:57 +00:00
..

Authentication with Cache Components (iron-session)

This example shows how to combine per-user authentication with Cache Components. It uses iron-session for encrypted cookie sessions, but the caching patterns apply to any session or auth library.

The home page renders a shared, prerendered shell, then renders content that reads the session behind a Suspense boundary:

  • Shared data (getAnnouncements) uses use cache and is part of the static shell.
  • The current user (getCurrentUser) uses use cache: private so it can read the session cookie while staying out of the shared, server-stored cache. It redirects when there is no signed-in user, so reads that start from it are protected.
  • Per-user data (lib/data.ts) exports getters that take no user id. They call getCurrentUser and pass the resolved id to an unexported plain use cache function with a cacheTag, so it caches on the server and is invalidated with updateTag.

The user data lives in memory (lib/data.ts) so the example runs without a database. Replace those functions with your own database queries, and verify passwords with a hashing library such as bcrypt.

Deploy your own

Deploy with Vercel

How to use

Execute create-next-app with npm, Yarn, pnpm, or Bun to bootstrap the example:

npx create-next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
yarn create next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
pnpm create next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
bunx create-next-app --example with-iron-session-cache-components with-iron-session-cache-components-app

Copy .env.example to .env.local and set SESSION_PASSWORD to a value of at least 32 characters:

cp .env.example .env.local
openssl rand -base64 32 # paste the output as SESSION_PASSWORD

Then run the development server and sign in with the demo account (ada@example.com / password):

npm run dev

Deploy it to the cloud with Vercel (Documentation).