- 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>
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) usesuse cacheand is part of the static shell. - The current user (
getCurrentUser) usesuse cache: privateso 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 callgetCurrentUserand pass the resolved id to an unexported plainuse cachefunction with acacheTag, so it caches on the server and is invalidated withupdateTag.
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
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).