Unverified Commit 8ff8f1b8 authored by Joseph's avatar Joseph Committed by GitHub

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: 's avatarAurora Scharff <66901228+aurorascharff@users.noreply.github.com>
Co-authored-by: 's avatarAurora Scharff <aurora.sofie@gmail.com>
Co-authored-by: 's avatarClaude Opus 5 <noreply@anthropic.com>
parent 0a1b0a79
---
title: How to use authentication with Cache Components
nav_title: Authentication with Cache Components
description: 'Learn how to read the user session, show authenticated UI without slowing down the page, and cache data derived from the session when Cache Components is enabled.'
related:
title: Next Steps
description: Learn more about authentication, caching, and prefetching in Next.js.
links:
- app/guides/authentication
- app/getting-started/caching
- app/getting-started/fetching-data
- app/guides/runtime-prefetching
- app/api-reference/directives/use-cache-private
- app/api-reference/functions/cacheTag
- app/api-reference/config/next-config-js/cacheComponents
---
With [Cache Components](/docs/app/getting-started/caching) enabled, a session read happens at request time, so it can't be prerendered into the static shell. Authenticated UI streams in behind a `<Suspense>` boundary instead, and data derived from the session can still be cached.
The examples use [iron-session](https://github.com/vvo/iron-session) for encrypted cookie sessions, but the patterns apply to any session or authentication library. For a complete, runnable version, see the [with-iron-session-cache-components example](https://github.com/vercel/next.js/tree/canary/examples/with-iron-session-cache-components).
## Prerequisites
Enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents):
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
```
This guide covers code patterns for authentication with Cache Components: reading the session at request time, streaming authenticated UI, and caching session-derived data. It assumes you're comfortable with Cache Components (if not, read [Caching](/docs/app/getting-started/caching) first) and that you already have a session set on login.
For the fundamentals this builds on, we recommend two guides:
- [Authentication](/docs/app/guides/authentication) covers sign-up, login, session management, authorization, and the Data Access Layer.
- [Data Security](/docs/app/guides/data-security) covers keeping data access on the server and sensitive data off the client.
## Migrating an existing app
With Cache Components enabled, instant navigation validation flags every route that reads the session, because a request read can't be prerendered into the static shell. You don't have to resolve them all before shipping. Set [`export const instant = false`](/docs/app/guides/instant-navigation#opting-out) on the page or layout to let it keep blocking on the server, then adopt the patterns below one route at a time. For the full migration workflow, see [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-components#following-validation).
## Step 1: Read the current user
Reading the current user reads the session cookie, then looks the user up. A request read can't be part of the static shell, so it always sits behind a [`<Suspense>`](/docs/app/api-reference/file-conventions/loading) boundary and streams in on every navigation.
Because a user session is valid for a period of time, adding a cache lifetime lets the framework prefetch that content ahead of time.
The server-side directives can't give it that lifetime, though: neither a plain [`use cache`](/docs/app/api-reference/directives/use-cache) nor [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) can call `cookies()`, and you can't [extract the value and pass it in](/docs/app/getting-started/caching#passing-runtime-values-to-cached-functions) either, because:
- A session helper reads the cookie deep inside its own code, so there's nothing to lift out.
- Validating it compares a token's expiry against the current time (iron-session's `unsealData` rejects an expired seal), so the read is request- and time-dependent.
That's what [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) is for: it reads `cookies()` and `headers()` directly, keeping the result in the browser only, never on the server.
A private scope stays in the browser, so it never caches on the server. To cache on the server instead, extract a value (the `userId`, for example) and pass it into a plain [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote). The same pattern caches data derived from the session, covered in [Step 4](#step-4-cache-session-derived-data).
```tsx filename="lib/session.ts"
import 'server-only'
import { cookies } from 'next/headers'
import { sealData, unsealData } from 'iron-session'
export type SessionData = {
userId?: string
}
const COOKIE_NAME = 'app_session'
const password = process.env.SESSION_PASSWORD!
export async function getSession(): Promise<SessionData> {
const cookie = (await cookies()).get(COOKIE_NAME)?.value
if (!cookie) {
return {}
}
return unsealData<SessionData>(cookie, { password })
}
```
```tsx filename="lib/auth.ts"
import 'server-only'
import { redirect } from 'next/navigation'
import { getSession } from './session'
import { findUserById } from './data'
export type User = {
id: string
name: string
}
export async function getCurrentUser(): Promise<User> {
'use cache: private'
const { userId } = await getSession()
if (!userId) {
redirect('/login')
}
const user = await findUserById(userId)
if (!user) {
redirect('/login')
}
return { id: user.id, name: user.name }
}
```
The `redirect()` calls throw to interrupt rendering rather than return a value, so they aren't cached. Only a resolved user is.
> **Good to know:** `use cache: private` accepts `cookies()`, `headers()`, and `searchParams`, but not [`connection()`](/docs/app/api-reference/functions/connection). See [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) for the full list.
## Step 2: Show the user without blocking the page
A component that reads the session must sit behind a [`<Suspense>`](/docs/app/api-reference/file-conventions/loading) boundary. With Cache Components, reading `cookies()` outside a boundary is a build error. The boundary is also what keeps the rest of the page fast. Anything outside it prerenders into the [static shell](/docs/app/getting-started/caching#prerendering) and loads instantly, as long as it's static or wrapped in [`use cache`](/docs/app/api-reference/directives/use-cache) and doesn't read runtime data of its own. Only the section behind the boundary waits for the request.
```tsx filename="app/page.tsx"
import { Suspense } from 'react'
import { getCurrentUser } from '@/lib/auth'
import { getAnnouncements } from '@/lib/data'
export default function Page() {
return (
<main>
{/* Cached, so it prerenders into the static shell */}
<Announcements />
{/* Reads the session, so it streams in behind the boundary */}
<Suspense fallback={<p>Loading your dashboard…</p>}>
<Dashboard />
</Suspense>
</main>
)
}
async function Announcements() {
'use cache'
const announcements = await getAnnouncements()
return (
<ul>
{announcements.map((announcement) => (
<li key={announcement}>{announcement}</li>
))}
</ul>
)
}
async function Dashboard() {
const user = await getCurrentUser()
return <h1>Welcome, {user.name}</h1>
}
```
Keep the session read out of a layout's top level, too. A top-level `await` on the session in a layout holds the whole segment, including `{children}`, behind that request, so push it into a component inside a boundary. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down).
> **Good to know:** `getCurrentUser` reads the session, checks it, and returns a narrow user. Centralizing those reads in one function is the [Data Access Layer](/docs/app/guides/authentication#creating-a-data-access-layer-dal) pattern.
## Step 3: Share the user across components
You don't have to read the session again in every component that needs the user. Read it once, then hand it to as many Server and Client Components as you like from inside the same boundary.
Server Components can call `getCurrentUser()` directly. To reach Client Components without prop drilling, create the promise once, pass it through context, and unwrap it with [`use()`](https://react.dev/reference/react/use). For the general pattern, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider). Because `getCurrentUser` reads the request, create its promise inside the Suspense boundary, not at the top of a layout.
```tsx filename="app/user-provider.tsx"
'use client'
import { createContext, use } from 'react'
import type { ReactNode } from 'react'
import type { User } from '@/lib/auth'
const UserContext = createContext<Promise<User> | null>(null)
export function UserProvider({
userPromise,
children,
}: {
userPromise: Promise<User>
children: ReactNode
}) {
return <UserContext value={userPromise}>{children}</UserContext>
}
export function useUser() {
const userPromise = use(UserContext)
if (!userPromise) {
throw new Error('useUser must be used within a UserProvider')
}
return use(userPromise)
}
```
The Server Component behind the boundary creates the promise and hands it to the provider without awaiting it. Each consumer then resolves it behind its own boundary, so the shared chrome renders without waiting on the session:
```tsx filename="app/page.tsx"
function Dashboard() {
const userPromise = getCurrentUser()
return (
<UserProvider userPromise={userPromise}>
<Suspense fallback={<span>Loading…</span>}>
<UserBadge />
</Suspense>
</UserProvider>
)
}
```
Client Components call `useUser()` to get the current user. Because `use()` suspends until the promise resolves, keep the component behind a `<Suspense>` boundary:
```tsx filename="app/user-badge.tsx"
'use client'
import { useUser } from './user-provider'
export function UserBadge() {
const user = useUser()
return <span>Signed in as {user.name}</span>
}
```
> **Good to know:** Expose only what the client needs. The `getCurrentUser` helper returns a narrow `{ id, name }` rather than the raw session. To keep sensitive fields from reaching the client, see [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue).
## Step 4: Cache session-derived data
Now that you have the user, you can cache the data you fetch for them in one of two ways. Passing the user id into a plain [`use cache`](/docs/app/api-reference/directives/use-cache) function keeps the result on the server, keyed by the id (it becomes part of the [cache key](/docs/app/api-reference/directives/use-cache#cache-keys)), where a [`cacheTag`](/docs/app/api-reference/functions/cacheTag) can invalidate it later. Reading it inside a [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) scope keeps it in the browser only, never on the server, which matters when requirements forbid storing certain data server-side, even ephemerally. The example passes the id, since these notes are tagged and refreshed when they change.
A plain `use cache` scope can't read `cookies()`, so the exported function resolves the user and passes just the id to the cached function:
```tsx filename="lib/data.ts"
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import { getCurrentUser } from './auth'
export async function getNotes() {
const user = await getCurrentUser()
return getNotesByUserId(user.id)
}
async function getNotesByUserId(userId: string) {
'use cache'
cacheTag(`notes:${userId}`)
cacheLife('minutes')
return db.query.notes.findMany({
where: (notes, { eq }) => eq(notes.userId, userId),
})
}
```
Keep `getNotesByUserId` unexported so a caller can't request another user's notes by passing a different id. Resolving the user inside the exported getter is what makes that safe. See [Data Security](/docs/app/guides/data-security#data-access-layer).
Call it from a Server Component that renders the notes. There's no user id to pass, and the `getCurrentUser()` call inside the getter hits the private cache, so the session isn't read again:
```tsx filename="app/page.tsx"
async function Notes() {
const notes = await getNotes()
// ...
}
```
> **Good to know: cache keys and tags are stored in plain text.** A cached function's arguments and captured variables are serialized into its cache key, and `cacheTag` values are stored as written. Neither is hashed: the default cache holds them as plain-text map keys and tag lists, and a [remote cache](/docs/app/api-reference/directives/use-cache-remote) receives them the same way. Key and tag on a stable identifier like the user id, and keep secrets and sensitive personal data (tokens, passwords, raw emails) out of arguments and tags.
On the server, plain `use cache` keeps the entry in memory as a best effort: it's evicted under pressure and, in serverless, doesn't persist across instances. If that data must survive across instances and requests, opt into [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) for durable, shared storage, where [the cache key you choose](/docs/app/api-reference/directives/use-cache-remote#cache-key-considerations) drives your hit rate.
## Step 5: Update session-derived data
When a [Server Action](/docs/app/getting-started/mutating-data) changes a user's data, call [`updateTag`](/docs/app/api-reference/functions/updateTag) with the same tag to refresh the cached entry. Re-read the session inside the action so it authorizes itself rather than trusting the client. See [authentication with Server Actions](/docs/app/guides/authentication#server-actions) for why this matters.
```ts filename="app/actions.ts"
'use server'
import { redirect } from 'next/navigation'
import { updateTag } from 'next/cache'
import { getSession } from '@/lib/session'
import { saveNote } from '@/lib/data'
export async function addNote(formData: FormData) {
const { userId } = await getSession()
if (!userId) {
redirect('/login')
}
const note = String(formData.get('note') ?? '').trim()
if (note) {
await saveNote(userId, note)
updateTag(`notes:${userId}`)
}
}
```
## Step 6: Make authenticated navigations instant
Cached reads already have a lifetime, so this mostly happens on its own. A `use cache: private` scope uses the [`default` profile](/docs/app/api-reference/functions/cacheLife#preset-cache-profiles) (a five-minute `stale`) unless you set one, and a route that reads the session produces a per-session [App Shell](/docs/app/glossary#app-shell) with the authenticated content, prefetched and cached per session. Navigations to it are already instant.
Two things keep it that way:
- If you tune the lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife), keep `stale` at 30 seconds or more. Below that, the scope drops out of prefetching. See [`cacheLife` client cache behavior](/docs/app/api-reference/functions/cacheLife#client-cache-behavior).
- A route that _also_ depends on the URL (a `params` or `searchParams` value) needs [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) on the links pointing at it. That opts into [runtime prefetching](/docs/app/guides/runtime-prefetching), which resolves the per-link data ahead of the click.
```tsx filename="app/page.tsx"
<Link href={`/notes/${note.id}`} prefetch={true}>
{note.text}
</Link>
```
The destination needs [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for this, so enable the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag or set `prefetch = 'partial'` on the segment. Add the prop where the wait is worth it: a runtime prefetch costs one server invocation per link, so a sidebar of `/chat/[id]` links pays that cost per item.
## Common pitfalls
- **Reading `cookies()` or `headers()` inside a plain `use cache` function.** This throws. Read the request outside and pass the value in, or use `use cache: private`.
- **Putting secrets or personal data in cache keys or tags.** Arguments and `cacheTag` values are stored in plain text. Key and tag on a stable identifier, not on sensitive input.
- **Trusting the client for authorization.** UI checks hide elements, but they don't protect data. Re-verify the session in every Server Action and [Route Handler](/docs/app/api-reference/file-conventions/route), close to the data. See [Authorization](/docs/app/guides/authentication#authorization).
......@@ -24,6 +24,8 @@ This diagram shows the authentication flow using React and Next.js features:
The examples on this page walk through basic username and password auth for educational purposes. While you can implement a custom auth solution, for increased security and simplicity, we recommend using an authentication library. These offer built-in solutions for authentication, session management, and authorization, as well as additional features such as social logins, multi-factor authentication, and role-based access control. You can find a list in the [Auth Libraries](#auth-libraries) section.
> **Good to know:** With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, reading the session and caching per-user data follow specific rules. See [Authentication with Cache Components](/docs/app/guides/authentication-with-cache-components).
## Authentication
<AppOnly>
......@@ -1363,7 +1365,7 @@ Session and user data often appear in shell UI (header, nav) that repeats across
If only part of the shell needs session data (for example, a user menu), move the `await` into a nested Server Component and wrap it in `<Suspense>` so the rest of the page streams first. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down) for the pattern.
Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a [Context Provider](#context-providers). To share data across multiple Server Components without re-fetching, see [Reusing data with `React.cache`](/docs/app/getting-started/fetching-data#reusing-data-with-reactcache).
Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a context provider. For that pattern, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider), and use React's [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) API to keep sensitive session fields from reaching the client.
#### Auth checks in page components
......@@ -1550,60 +1552,6 @@ export async function GET() {
The example above demonstrates a Route Handler with a two-tier security check. It first checks for an active session, and then verifies if the logged-in user is an 'admin'.
## Context Providers
Using context providers for auth works due to [interleaving](/docs/app/getting-started/server-and-client-components#interleaving-server-and-client-components). However, React `context` is not supported in Server Components, making them only applicable to Client Components.
This works, but any child Server Components will be rendered on the server first, and will not have access to the context provider’s session data:
```tsx filename="app/layout.tsx" switcher
import { ContextProvider } from 'auth-lib'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<ContextProvider>{children}</ContextProvider>
</body>
</html>
)
}
```
```tsx filename="app/ui/profile.tsx" switcher
'use client'
import { useSession } from "auth-lib";
export default function Profile() {
const { userId } = useSession();
const { data } = useSWR(`/api/user/${userId}`, fetcher)
return (
// ...
);
}
```
```jsx filename="app/ui/profile.jsx" switcher
'use client'
import { useSession } from "auth-lib";
export default function Profile() {
const { userId } = useSession();
const { data } = useSWR(`/api/user/${userId}`, fetcher)
return (
// ...
);
}
```
If session data is needed in Client Components (e.g. for client-side data fetching), use React’s [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) API to prevent sensitive session data from being exposed to the client.
For the general pattern of passing server-fetched data through context and reading it with `use()`, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider).
</AppOnly>
<PagesOnly>
......
......@@ -10,6 +10,7 @@ related:
- app/getting-started/caching
- app/guides/preserving-ui-state
- app/guides/incremental-static-regeneration-cache-components
- app/guides/authentication-with-cache-components
- app/api-reference/functions/generate-static-params
- app/api-reference/config/next-config-js/cacheComponents
---
......
# A secret used to encrypt the session cookie. Must be at least 32 characters.
# Generate one with: openssl rand -base64 32
SESSION_PASSWORD=
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Authentication with Cache Components (iron-session)
This example shows how to combine per-user authentication with [Cache Components](https://nextjs.org/docs/app/getting-started/caching). It uses [iron-session](https://github.com/vvo/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`](https://nextjs.org/docs/app/api-reference/directives/use-cache) and is part of the static shell.
- **The current user** (`getCurrentUser`) uses [`use cache: private`](https://nextjs.org/docs/app/api-reference/directives/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`](https://nextjs.org/docs/app/api-reference/functions/cacheTag), so it caches on the server and is invalidated with [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/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](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-iron-session-cache-components&project-name=with-iron-session-cache-components&repository-name=with-iron-session-cache-components&env=SESSION_PASSWORD)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), [pnpm](https://pnpm.io), or [Bun](https://bun.sh/docs/cli/bunx) 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 (`ada@example.com` / `password`):
```bash
npm run dev
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
"use server";
import { redirect } from "next/navigation";
import { getSession, destroySession } from "@/lib/session";
import { addUserNote } from "@/lib/data";
export async function logout() {
await destroySession();
redirect("/login");
}
export async function addNote(formData: FormData) {
// Re-check the session inside the action. Never trust the client to tell you
// who the current user is.
const session = await getSession();
if (!session.userId) {
redirect("/login");
}
const note = String(formData.get("note") ?? "").trim();
if (note) {
await addUserNote(session.userId, note);
}
}
import type { ReactNode } from "react";
export const metadata = {
title: "iron-session + Cache Components",
description: "Authentication with Next.js Cache Components and iron-session.",
};
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
"use server";
import { redirect } from "next/navigation";
import { saveSession } from "@/lib/session";
import { verifyCredentials } from "@/lib/data";
export type LoginState = { error: string } | null;
export async function login(
_prevState: LoginState,
formData: FormData,
): Promise<LoginState> {
const email = String(formData.get("email") ?? "");
const password = String(formData.get("password") ?? "");
const userId = await verifyCredentials(email, password);
if (!userId) {
return { error: "These credentials do not match our records." };
}
await saveSession({ userId });
redirect("/");
}
"use client";
import { useActionState } from "react";
import { login, type LoginState } from "./actions";
export default function LoginPage() {
const [state, action, pending] = useActionState<LoginState, FormData>(
login,
null,
);
return (
<main>
<h1>Log in</h1>
<form action={action}>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
defaultValue="ada@example.com"
/>
</div>
<div>
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
defaultValue="password"
/>
</div>
{state?.error && <p>{state.error}</p>}
<button type="submit" disabled={pending}>
Log in
</button>
</form>
</main>
);
}
import { Suspense } from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getNote } from "@/lib/data";
async function Note({
params,
}: {
params: PageProps<"/notes/[id]">["params"];
}) {
const { id } = await params;
// `getNote()` resolves the user from the session, so a guessed id cannot
// reach another user's note.
const note = await getNote(id);
if (!note) {
notFound();
}
return <article>{note.text}</article>;
}
export default function NotePage({ params }: PageProps<"/notes/[id]">) {
return (
<main>
<Link href="/">← Back</Link>
<Suspense fallback={<p>Loading note…</p>}>
<Note params={params} />
</Suspense>
</main>
);
}
import { Suspense } from "react";
import Link from "next/link";
import { getCurrentUser } from "@/lib/auth";
import { getAnnouncements, getNotes } from "@/lib/data";
import { addNote, logout } from "./actions";
import { UserProvider } from "./user-provider";
import { UserBadge } from "./user-badge";
async function Announcements() {
const announcements = await getAnnouncements();
return (
<section>
<h2>Announcements</h2>
<ul>
{announcements.map((announcement) => (
<li key={announcement}>{announcement}</li>
))}
</ul>
</section>
);
}
async function Notes() {
// `getNotes()` resolves the user from the session, so there is no id to pass.
const notes = await getNotes();
return (
<section>
<h2>Your notes</h2>
<ul>
{notes.map((note) => (
<li key={note.id}>
<Link href={`/notes/${note.id}`} prefetch={true}>
{note.text}
</Link>
</li>
))}
</ul>
</section>
);
}
function Dashboard() {
// Create the promise once and hand it to the provider without awaiting it, so
// the dashboard chrome renders immediately and each consumer resolves the
// session behind its own boundary.
const userPromise = getCurrentUser();
return (
<UserProvider userPromise={userPromise}>
<section>
<Suspense fallback={<span>Loading…</span>}>
<UserBadge />
</Suspense>
<form action={logout}>
<button type="submit">Log out</button>
</form>
</section>
<Suspense fallback={<p>Loading your notes…</p>}>
<Notes />
</Suspense>
<form action={addNote}>
<input name="note" placeholder="Add a note" />
<button type="submit">Add</button>
</form>
</UserProvider>
);
}
export default function Page() {
return (
<main>
{/* Shared content. Prerendered into the static shell. */}
<Announcements />
{/* Reads the session, so it renders into the per-session App Shell
instead of the shared static shell. */}
<Suspense fallback={<p>Loading your dashboard…</p>}>
<Dashboard />
</Suspense>
</main>
);
}
"use client";
import { useUser } from "./user-provider";
export function UserBadge() {
const user = useUser();
return <span>Signed in as {user.name}</span>;
}
"use client";
import { createContext, use } from "react";
import type { ReactNode } from "react";
import type { User } from "@/lib/auth";
const UserContext = createContext<Promise<User> | null>(null);
export function UserProvider({
userPromise,
children,
}: {
userPromise: Promise<User>;
children: ReactNode;
}) {
return <UserContext value={userPromise}>{children}</UserContext>;
}
export function useUser() {
const userPromise = use(UserContext);
if (!userPromise) {
throw new Error("useUser must be used within a UserProvider");
}
return use(userPromise);
}
import "server-only";
import { redirect } from "next/navigation";
import { cacheLife } from "next/cache";
import { getSession } from "./session";
import { findUserById } from "./data";
export type User = {
id: string;
name: string;
};
// Reads the session cookie, so it must run on every request and cannot live in
// a plain `use cache` scope. `use cache: private` lets it read the cookie while
// keeping the result out of the shared, server-stored cache. Cached scopes are
// prefetchable by default; a `stale` of at least 30 seconds keeps it that way.
export async function getCurrentUser(): Promise<User> {
"use cache: private";
cacheLife({ stale: 60 });
const { userId } = await getSession();
if (!userId) {
redirect("/login");
}
const user = await findUserById(userId);
if (!user) {
redirect("/login");
}
return { id: user.id, name: user.name };
}
import "server-only";
import { cacheLife, cacheTag, updateTag } from "next/cache";
import { getCurrentUser } from "./auth";
// This file stands in for your database. The data lives in memory and resets
// when the server restarts. In a real app, replace these functions with calls
// to your database and verify passwords with a hashing library such as bcrypt.
type UserRecord = {
id: string;
name: string;
email: string;
// Demo only. Never store plaintext passwords in a real application.
password: string;
};
export type Note = {
id: string;
text: string;
};
const users: UserRecord[] = [
{
id: "1",
name: "Ada Lovelace",
email: "ada@example.com",
password: "password",
},
];
const notesByUserId = new Map<string, Note[]>([
["1", [{ id: "n1", text: "Finish the analytical engine notes." }]],
]);
export async function verifyCredentials(
email: string,
password: string,
): Promise<string | null> {
const user = users.find((u) => u.email === email);
if (!user || user.password !== password) {
return null;
}
return user.id;
}
export async function findUserById(id: string) {
return users.find((u) => u.id === id) ?? null;
}
// Shared data. It does not depend on the request, so a plain `use cache`
// scope stores it on the server and includes it in the static shell.
export async function getAnnouncements() {
"use cache";
cacheTag("announcements");
cacheLife("hours");
return [
"Cache Components is now enabled.",
"Session data streams in after the shell.",
];
}
// Takes the id as an argument instead of reading the request, so this stays a
// plain `use cache` scope. The result is stored on the server, keyed by
// `userId`, and tagged for targeted invalidation.
async function getNotesByUserId(userId: string): Promise<Note[]> {
"use cache";
cacheTag(`notes:${userId}`);
cacheLife("minutes");
return notesByUserId.get(userId) ?? [];
}
async function getNoteById(
userId: string,
noteId: string,
): Promise<Note | null> {
"use cache";
cacheTag(`notes:${userId}`);
cacheLife("minutes");
const notes = notesByUserId.get(userId) ?? [];
return notes.find((note) => note.id === noteId) ?? null;
}
// The exported readers resolve the user from the session, so there is no id for
// a caller to get wrong.
export async function getNotes(): Promise<Note[]> {
const user = await getCurrentUser();
return getNotesByUserId(user.id);
}
export async function getNote(noteId: string): Promise<Note | null> {
const user = await getCurrentUser();
return getNoteById(user.id, noteId);
}
// Writes go through a Server Action that has already checked the session, so
// this takes the verified id. See Step 5 of the guide.
export async function addUserNote(userId: string, text: string) {
const existing = notesByUserId.get(userId) ?? [];
const note: Note = { id: crypto.randomUUID(), text };
notesByUserId.set(userId, [...existing, note]);
// Invalidate this user's cached notes so the next read returns fresh data.
updateTag(`notes:${userId}`);
}
import "server-only";
import { cookies } from "next/headers";
import { sealData, unsealData } from "iron-session";
export type SessionData = {
userId?: string;
};
const COOKIE_NAME = "app_session";
const password = process.env.SESSION_PASSWORD!;
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
};
export async function getSession(): Promise<SessionData> {
const cookie = (await cookies()).get(COOKIE_NAME)?.value;
if (!cookie) {
return {};
}
try {
return await unsealData<SessionData>(cookie, { password });
} catch {
// An expired, tampered, or otherwise unsealable cookie (for example after
// SESSION_PASSWORD is rotated) is treated the same as no session, so
// callers redirect to /login instead of hitting the error boundary.
return {};
}
}
export async function saveSession(data: SessionData) {
const sealed = await sealData(data, { password });
(await cookies()).set(COOKIE_NAME, sealed, cookieOptions);
}
export async function destroySession() {
(await cookies()).delete(COOKIE_NAME);
}
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
};
export default nextConfig;
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"iron-session": "^8.0.4",
"next": "latest",
"react": "latest",
"react-dom": "latest"
},
"devDependencies": {
"@types/node": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
"typescript": "6.0.3"
}
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment