Unverified Commit b4a4c055 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: use auth interruption APIs in examples (#99698)

## Summary

- Replace generic `Unauthorized` and `Forbidden` errors with the stable
`unauthorized()` and `forbidden()` APIs across the mutating data, forms,
Server Actions, data security, and `use server` documentation.
- Distinguish unauthenticated requests from authenticated users who lack
permission in the security examples.
- Link to the API references and explain that the functions render the
matching fallback files.

This PR is stacked on #99696, which adds the complete pattern to the
error-handling guide.

## Verification

- `pnpm prettier --with-node-modules --ignore-path .prettierignore
--write docs/01-app/01-getting-started/07-mutating-data.mdx
docs/01-app/02-guides/data-security.mdx docs/01-app/02-guides/forms.mdx
docs/01-app/02-guides/server-actions.mdx
docs/01-app/03-api-reference/01-directives/use-server.mdx`
- `pnpm exec eslint --config eslint.config.mjs --fix
docs/01-app/01-getting-started/07-mutating-data.mdx
docs/01-app/02-guides/data-security.mdx docs/01-app/02-guides/forms.mdx
docs/01-app/02-guides/server-actions.mdx
docs/01-app/03-api-reference/01-directives/use-server.mdx`
- `NO_UPDATE_NOTIFIER=1 pnpm exec alex
docs/01-app/01-getting-started/07-mutating-data.mdx
docs/01-app/02-guides/data-security.mdx docs/01-app/02-guides/forms.mdx
docs/01-app/02-guides/server-actions.mdx
docs/01-app/03-api-reference/01-directives/use-server.mdx --quiet`
- Not run: framework tests (documentation-only change)

<!-- NEXT_JS_LLM -->
parent 8051552d
......@@ -9,6 +9,7 @@ related:
- app/api-reference/functions/revalidatePath
- app/api-reference/functions/revalidateTag
- app/api-reference/functions/redirect
- app/api-reference/functions/unauthorized
---
You can mutate data in Next.js using [React Server Functions](https://react.dev/reference/rsc/server-functions). This page will go through how you can [create](#creating-server-functions) and [invoke](#invoking-server-functions) Server Functions. For Next.js-specific behaviors (single-roundtrip response, sequential dispatch, security, deployment), see [Server Actions and Mutations](/docs/app/guides/server-actions).
......@@ -37,14 +38,17 @@ Behind the scenes, actions use the `POST` method, and only this HTTP method can
A Server Function can be defined by using the [`use server`](https://react.dev/reference/rsc/use-server) directive. You can place the directive at the top of an **asynchronous** function to mark the function as a Server Function, or at the top of a separate file to mark all exports of that file.
The following example calls [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated. Next.js renders the nearest [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized) fallback.
```ts filename="app/lib/actions.ts" switcher
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const title = formData.get('title')
......@@ -58,7 +62,7 @@ export async function deletePost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const id = formData.get('id')
......@@ -71,12 +75,13 @@ export async function deletePost(formData: FormData) {
```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const title = formData.get('title')
......@@ -90,7 +95,7 @@ export async function deletePost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const id = formData.get('id')
......@@ -244,11 +249,12 @@ export function Form() {
'use server'
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const title = formData.get('title')
......@@ -263,11 +269,12 @@ export async function createPost(formData: FormData) {
'use server'
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const title = formData.get('title')
......@@ -387,11 +394,12 @@ After a mutation, you may want to refresh the current page to show the latest da
import { auth } from '@/lib/auth'
import { refresh } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function updatePost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
// Mutate data
// ...
......@@ -405,11 +413,12 @@ export async function updatePost(formData: FormData) {
import { auth } from '@/lib/auth'
import { refresh } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function updatePost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
// Mutate data
// ...
......@@ -427,12 +436,13 @@ After performing a mutation, you can revalidate the Next.js cache and show the u
```ts filename="app/lib/actions.ts" switcher
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
// Mutate data
// ...
......@@ -444,12 +454,13 @@ export async function createPost(formData: FormData) {
```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
export async function createPost(formData) {
'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
// Mutate data
// ...
......@@ -466,12 +477,12 @@ You may want to redirect the user to a different page after a mutation. You can
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { redirect, unauthorized } from 'next/navigation'
export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
// Mutate data
// ...
......@@ -486,12 +497,12 @@ export async function createPost(formData: FormData) {
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { redirect, unauthorized } from 'next/navigation'
export async function createPost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
// Mutate data
// ...
......
......@@ -338,23 +338,29 @@ export default async function Page() {
A page-level authentication check does not extend to the Server Actions defined within it. Always re-verify inside the action:
```tsx filename="app/admin/page.tsx" highlight={13,14,15,16}
```tsx filename="app/admin/page.tsx" highlight={16,17,18,19,20,21,22,23}
import { auth } from '@/lib/auth'
import { redirect } from 'next/navigation'
import { forbidden, redirect, unauthorized } from 'next/navigation'
export default async function AdminPage() {
const session = await auth()
if (!session?.user?.isAdmin) {
if (!session?.user) {
redirect('/login')
}
if (!session.user.isAdmin) {
forbidden()
}
return (
<form
action={async () => {
'use server'
const session = await auth()
if (!session?.user?.isAdmin) {
throw new Error('Unauthorized')
if (!session?.user) {
unauthorized()
}
if (!session.user.isAdmin) {
forbidden()
}
await db.record.deleteMany()
}}
......@@ -365,27 +371,30 @@ export default async function AdminPage() {
}
```
The highlighted `auth()` check inside the action is critical. The page-level redirect on line 6 controls which UI is rendered, but the Server Action is a separate entry point and must verify the caller on its own.
The page redirects unauthenticated visitors to sign in. The highlighted checks inside the action are still required because a Server Action is a separate entry point that may be called directly.
Beyond authentication (is the user logged in?), remember to check **authorization** (does this user have permission to act on this specific resource?). This prevents [Insecure Direct Object Reference (IDOR)](https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html) vulnerabilities:
Call [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated. Call [`forbidden()`](/docs/app/api-reference/functions/forbidden) when the user is authenticated but lacks permission. Next.js renders the nearest [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized) or [`forbidden.js`](/docs/app/api-reference/file-conventions/forbidden) fallback.
```tsx filename="app/actions.ts"
'use server'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const post = await db.post.findUnique({ where: { id: postId } })
// Check that the user owns this resource
if (post.authorId !== session.user.id) {
throw new Error('Forbidden')
forbidden()
}
await db.post.delete({ where: { id: postId } })
......@@ -403,17 +412,18 @@ import 'server-only'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const post = await db.post.findUnique({ where: { id: postId } })
if (post.authorId !== session.user.id) {
throw new Error('Forbidden')
forbidden()
}
await db.post.delete({ where: { id: postId } })
......@@ -445,13 +455,14 @@ Server Action return values are serialized and sent to the client. Only return w
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
import { unauthorized } from 'next/navigation'
// BAD: Returns the full database record, which may include
// internal fields the client should not see.
export async function updateUser(data: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
return db.user.update({
where: { id: session.user.id },
......@@ -463,7 +474,7 @@ export async function updateUser(data: FormData) {
export async function updateUserSafe(data: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
await db.user.update({
where: { id: session.user.id },
......
......@@ -9,6 +9,8 @@ React Server Actions are [Server Functions](https://react.dev/reference/rsc/serv
> [!WARNING]
> Always verify [authentication and authorization](/docs/app/guides/authentication) inside each Server Action, even if the form is only rendered on an authenticated page. See the [Data Security guide](/docs/app/guides/data-security) for more details.
Call [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated. Next.js renders the nearest `unauthorized.js` fallback.
## How it works
React extends the HTML [`<form>`](https://developer.mozilla.org/docs/Web/HTML/Element/form) element to allow Server Actions to be invoked with the [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/form#action) attribute.
......@@ -17,6 +19,7 @@ When used in a form, the function automatically receives the [`FormData`](https:
```tsx filename="app/invoices/page.tsx" switcher
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export default function Page() {
async function createInvoice(formData: FormData) {
......@@ -24,7 +27,7 @@ export default function Page() {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const rawFormData = {
......@@ -43,6 +46,7 @@ export default function Page() {
```jsx filename="app/invoices/page.js" switcher
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export default function Page() {
async function createInvoice(formData) {
......@@ -50,7 +54,7 @@ export default function Page() {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const rawFormData = {
......
......@@ -51,12 +51,13 @@ A re-render is included in the same response when the action does any of these:
'use server'
import { revalidatePath } from 'next/cache'
import { unauthorized } from 'next/navigation'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) throw new Error('Unauthorized')
if (!session?.user) unauthorized()
await db.post.create({
data: {
......@@ -94,21 +95,22 @@ For end-to-end patterns including a Data Access Layer, return-value tainting, an
Destructive operations like deletes may warrant stronger handling, such as elevated session checks or re-authentication, and a loud failure when those checks miss.
```ts filename="app/posts/actions.ts" highlight={6,7,8}
```ts filename="app/posts/actions.ts" highlight={4,7,8,9}
'use server'
import { auth } from '@/lib/auth'
import { forbidden, unauthorized } from 'next/navigation'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) throw new Error('Unauthorized')
if (!(await canDelete(session.user, postId))) throw new Error('Forbidden')
if (!session?.user) unauthorized()
if (!(await canDelete(session.user, postId))) forbidden()
await db.post.delete({ where: { id: postId } })
}
```
You can also throw [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) and [`forbidden()`](/docs/app/api-reference/functions/forbidden) from `next/navigation` instead, so Next.js renders the corresponding `unauthorized.tsx` / `forbidden.tsx` UI segment automatically.
Call [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when the request is not authenticated. Call [`forbidden()`](/docs/app/api-reference/functions/forbidden) when the user is authenticated but lacks permission. Next.js renders the corresponding `unauthorized.tsx` or `forbidden.tsx` fallback.
For example, a client legitimately tells the server _which_ item to act on, but it should not supply the row's contents or ownership. Send a reference (typically an ID) plus the user's change, and re-read the rest from a trusted source using the session. Schema validation (zod or similar) only checks the _shape_ of the input. A well-formed `Item` object can still refer to a row the caller does not own.
......
......@@ -9,17 +9,18 @@ For Next.js-specific Server Action behaviors (response model, security, configur
## Using `use server` at the top of a file
The following example shows a file with a `use server` directive at the top. All functions in the file are executed on the server.
The following example shows a file with a `use server` directive at the top. All functions in the file are executed on the server. It calls [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated, which renders the nearest [`unauthorized.js`](/docs/app/api-reference/file-conventions/unauthorized) fallback.
```tsx filename="app/actions.ts" highlight={1} switcher
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createUser(data: { name: string; email: string }) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const user = await db.user.create({ data })
......@@ -31,11 +32,12 @@ export async function createUser(data: { name: string; email: string }) {
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function createUser(data) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const user = await db.user.create({ data })
......@@ -53,11 +55,12 @@ Assuming you have a `fetchUsers` Server Function in `actions.ts`:
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function fetchUsers() {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const users = await db.user.findMany({
......@@ -71,11 +74,12 @@ export async function fetchUsers() {
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
import { unauthorized } from 'next/navigation'
export async function fetchUsers() {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const users = await db.user.findMany({
......@@ -157,32 +161,36 @@ Design your data access functions as secure primitives: validate inputs, check a
Always authenticate and authorize users before performing sensitive server-side operations. Read authentication from cookies or headers rather than accepting tokens as function parameters.
```tsx filename="app/actions.ts" highlight={1,7,8,9,10} switcher
Call [`unauthorized()`](/docs/app/api-reference/functions/unauthorized) when a request is not authenticated. Next.js renders the nearest `unauthorized.js` fallback.
```tsx filename="app/actions.ts" highlight={1,5,8,9,10,11} switcher
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' // Your authentication library
import { unauthorized } from 'next/navigation'
export async function createUser(data: { name: string; email: string }) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const newUser = await db.user.create({ data })
return { id: newUser.id, name: newUser.name }
}
```
```jsx filename="app/actions.js" highlight={1,7,8,9,10} switcher
```jsx filename="app/actions.js" highlight={1,5,8,9,10,11} switcher
'use server'
import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth' // Your authentication library
import { unauthorized } from 'next/navigation'
export async function createUser(data) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
unauthorized()
}
const newUser = await db.user.create({ data })
return { id: newUser.id, name: newUser.name }
......
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