Back to Next Js

Authentication with Cache Components (iron-session)

examples/with-iron-session-cache-components/README.md

16.3.33.1 KB
Original Source

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

How to use

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

bash
npx create-next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
bash
yarn create next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
bash
pnpm create next-app --example with-iron-session-cache-components with-iron-session-cache-components-app
bash
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:

bash
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):

bash
npm run dev

Deploy it to the cloud with Vercel (Documentation).