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
This diff is collapsed.
...@@ -24,6 +24,8 @@ This diagram shows the authentication flow using React and Next.js features: ...@@ -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. 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 ## Authentication
<AppOnly> <AppOnly>
...@@ -1363,7 +1365,7 @@ Session and user data often appear in shell UI (header, nav) that repeats across ...@@ -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. 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 #### Auth checks in page components
...@@ -1550,60 +1552,6 @@ export async function GET() { ...@@ -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'. 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> </AppOnly>
<PagesOnly> <PagesOnly>
......
...@@ -10,6 +10,7 @@ related: ...@@ -10,6 +10,7 @@ related:
- app/getting-started/caching - app/getting-started/caching
- app/guides/preserving-ui-state - app/guides/preserving-ui-state
- app/guides/incremental-static-regeneration-cache-components - app/guides/incremental-static-regeneration-cache-components
- app/guides/authentication-with-cache-components
- app/api-reference/functions/generate-static-params - app/api-reference/functions/generate-static-params
- app/api-reference/config/next-config-js/cacheComponents - 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