examples/with-iron-session-cache-components/README.md
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:
getAnnouncements) uses use cache and is part of the static shell.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.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.
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 ([email protected] / password):
npm run dev
Deploy it to the cloud with Vercel (Documentation).