Unverified Commit 3162af8d authored by Joseph's avatar Joseph Committed by GitHub

docs: More Server Actions security guidance across docs (#90878)

Closes:
https://linear.app/vercel/issue/DOC-6108/server-action-security-lift
parent ae9c9d6c
...@@ -27,6 +27,9 @@ When an action is invoked, Next.js can return both the updated UI and new data i ...@@ -27,6 +27,9 @@ When an action is invoked, Next.js can return both the updated UI and new data i
Behind the scenes, actions use the `POST` method, and only this HTTP method can invoke them. Behind the scenes, actions use the `POST` method, and only this HTTP method can invoke them.
> [!WARNING]
> Server Functions are reachable via direct POST requests, not just through your application's UI. Always verify authentication and authorization inside every Server Function. See the [Data Security guide](/docs/app/guides/data-security#authentication-and-authorization) for recommended patterns.
> **Good to know:** A Server Action is a Server Function used in a specific way (for handling form submissions and mutations). Server Function is the broader term. > **Good to know:** A Server Action is a Server Function used in a specific way (for handling form submissions and mutations). Server Function is the broader term.
## Creating Server Functions ## Creating Server Functions
...@@ -34,8 +37,15 @@ Behind the scenes, actions use the `POST` method, and only this HTTP method can ...@@ -34,8 +37,15 @@ 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. 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.
```ts filename="app/lib/actions.ts" switcher ```ts filename="app/lib/actions.ts" switcher
import { auth } from '@/lib/auth'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
'use server' 'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const title = formData.get('title') const title = formData.get('title')
const content = formData.get('content') const content = formData.get('content')
...@@ -45,16 +55,29 @@ export async function createPost(formData: FormData) { ...@@ -45,16 +55,29 @@ export async function createPost(formData: FormData) {
export async function deletePost(formData: FormData) { export async function deletePost(formData: FormData) {
'use server' 'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const id = formData.get('id') const id = formData.get('id')
// Verify the user owns this resource before deleting
// Mutate data // Mutate data
// Revalidate cache // Revalidate cache
} }
``` ```
```js filename="app/lib/actions.js" switcher ```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth'
export async function createPost(formData) { export async function createPost(formData) {
'use server' 'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const title = formData.get('title') const title = formData.get('title')
const content = formData.get('content') const content = formData.get('content')
...@@ -64,8 +87,14 @@ export async function createPost(formData) { ...@@ -64,8 +87,14 @@ export async function createPost(formData) {
export async function deletePost(formData) { export async function deletePost(formData) {
'use server' 'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const id = formData.get('id') const id = formData.get('id')
// Verify the user owns this resource before deleting
// Mutate data // Mutate data
// Revalidate cache // Revalidate cache
} }
...@@ -213,7 +242,14 @@ export function Form() { ...@@ -213,7 +242,14 @@ export function Form() {
```ts filename="app/actions.ts" switcher ```ts filename="app/actions.ts" switcher
'use server' 'use server'
import { auth } from '@/lib/auth'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const title = formData.get('title') const title = formData.get('title')
const content = formData.get('content') const content = formData.get('content')
...@@ -225,7 +261,14 @@ export async function createPost(formData: FormData) { ...@@ -225,7 +261,14 @@ export async function createPost(formData: FormData) {
```js filename="app/actions.js" switcher ```js filename="app/actions.js" switcher
'use server' 'use server'
import { auth } from '@/lib/auth'
export async function createPost(formData) { export async function createPost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const title = formData.get('title') const title = formData.get('title')
const content = formData.get('content') const content = formData.get('content')
...@@ -337,9 +380,14 @@ After a mutation, you may want to refresh the current page to show the latest da ...@@ -337,9 +380,14 @@ After a mutation, you may want to refresh the current page to show the latest da
```ts filename="app/lib/actions.ts" switcher ```ts filename="app/lib/actions.ts" switcher
'use server' 'use server'
import { auth } from '@/lib/auth'
import { refresh } from 'next/cache' import { refresh } from 'next/cache'
export async function updatePost(formData: FormData) { export async function updatePost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// Mutate data // Mutate data
// ... // ...
...@@ -350,9 +398,14 @@ export async function updatePost(formData: FormData) { ...@@ -350,9 +398,14 @@ export async function updatePost(formData: FormData) {
```js filename="app/lib/actions.js" switcher ```js filename="app/lib/actions.js" switcher
'use server' 'use server'
import { auth } from '@/lib/auth'
import { refresh } from 'next/cache' import { refresh } from 'next/cache'
export async function updatePost(formData) { export async function updatePost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// Mutate data // Mutate data
// ... // ...
...@@ -367,10 +420,15 @@ This refreshes the client router, ensuring the UI reflects the latest state. The ...@@ -367,10 +420,15 @@ This refreshes the client router, ensuring the UI reflects the latest state. The
After performing a mutation, you can revalidate the Next.js cache and show the updated data by calling [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) within the Server Function: After performing a mutation, you can revalidate the Next.js cache and show the updated data by calling [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) within the Server Function:
```ts filename="app/lib/actions.ts" switcher ```ts filename="app/lib/actions.ts" switcher
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
'use server' 'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// Mutate data // Mutate data
// ... // ...
...@@ -379,10 +437,15 @@ export async function createPost(formData: FormData) { ...@@ -379,10 +437,15 @@ export async function createPost(formData: FormData) {
``` ```
```js filename="app/actions.js" switcher ```js filename="app/actions.js" switcher
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
export async function createPost(formData) { export async function createPost(formData) {
'use server' 'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// Mutate data // Mutate data
// ... // ...
revalidatePath('/posts') revalidatePath('/posts')
...@@ -396,10 +459,15 @@ You may want to redirect the user to a different page after a mutation. You can ...@@ -396,10 +459,15 @@ You may want to redirect the user to a different page after a mutation. You can
```ts filename="app/lib/actions.ts" switcher ```ts filename="app/lib/actions.ts" switcher
'use server' 'use server'
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// Mutate data // Mutate data
// ... // ...
...@@ -411,10 +479,15 @@ export async function createPost(formData: FormData) { ...@@ -411,10 +479,15 @@ export async function createPost(formData: FormData) {
```js filename="app/actions.js" switcher ```js filename="app/actions.js" switcher
'use server' 'use server'
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export async function createPost(formData) { export async function createPost(formData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
// Mutate data // Mutate data
// ... // ...
......
...@@ -269,7 +269,7 @@ Next.js handles mutations with [Server Actions](https://react.dev/reference/rsc/ ...@@ -269,7 +269,7 @@ Next.js handles mutations with [Server Actions](https://react.dev/reference/rsc/
### Built-in Server Actions Security features ### Built-in Server Actions Security features
By default, when a Server Action is created and exported, it creates a public HTTP endpoint and should be treated with the same security assumptions and authorization checks. This means, even if a Server Action or utility function is not imported elsewhere in your code, it's still publicly accessible. By default, when a Server Action is created and exported, it is reachable via a direct POST request, not just through your application's UI. This means, even if a Server Action or utility function is not imported elsewhere in your code, it can still be called externally.
To improve security, Next.js has the following built-in features: To improve security, Next.js has the following built-in features:
...@@ -279,7 +279,7 @@ To improve security, Next.js has the following built-in features: ...@@ -279,7 +279,7 @@ To improve security, Next.js has the following built-in features:
> **Good to know**: > **Good to know**:
> >
> The IDs are created during compilation and are cached for a maximum of 14 days. They will be regenerated when a new build is initiated or when the build cache is invalidated. > The IDs are created during compilation and are cached for a maximum of 14 days. They will be regenerated when a new build is initiated or when the build cache is invalidated.
> This security improvement reduces the risk in cases where an authentication layer is missing. However, you should still treat Server Actions like public HTTP endpoints. > This security improvement reduces the risk in cases where an authentication layer is missing. However, you should still treat Server Actions as reachable via direct POST requests and verify authentication and authorization inside each one.
```jsx ```jsx
// app/actions.js // app/actions.js
...@@ -326,25 +326,147 @@ export default async function Page() { ...@@ -326,25 +326,147 @@ export default async function Page() {
### Authentication and authorization ### Authentication and authorization
You should always ensure that a user is authorized to perform an action. For example: 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}
import { auth } from '@/lib/auth'
import { redirect } from 'next/navigation'
export default async function AdminPage() {
const session = await auth()
if (!session?.user?.isAdmin) {
redirect('/login')
}
return (
<form
action={async () => {
'use server'
const session = await auth()
if (!session?.user?.isAdmin) {
throw new Error('Unauthorized')
}
await db.record.deleteMany()
}}
>
<button>Delete Records</button>
</form>
)
}
```
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.
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:
```tsx filename="app/actions.ts" ```tsx filename="app/actions.ts"
'use server' 'use server'
import { auth } from './lib' import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const post = await db.post.findUnique({ where: { id: postId } })
export function addItem() { // Check that the user owns this resource
const { user } = auth() if (post.authorId !== session.user.id) {
if (!user) { throw new Error('Forbidden')
throw new Error('You must be signed in to perform this action')
} }
// ... await db.post.delete({ where: { id: postId } })
} }
``` ```
Learn more about [Authentication](/docs/app/guides/authentication) in Next.js. Learn more about [Authentication](/docs/app/guides/authentication) in Next.js.
### Using a Data Access Layer for mutations
Just as we recommend a [Data Access Layer](#data-access-layer) for reading data, you can apply the same pattern to mutations. This keeps authentication, authorization, and database logic in a dedicated `server-only` module, while `"use server"` actions stay thin.
```ts filename="data/posts.ts"
import 'server-only'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const post = await db.post.findUnique({ where: { id: postId } })
if (post.authorId !== session.user.id) {
throw new Error('Forbidden')
}
await db.post.delete({ where: { id: postId } })
}
```
The `"use server"` action then delegates to the DAL:
```ts filename="app/actions.ts"
'use server'
import { deletePost } from '@/data/posts'
import { revalidatePath } from 'next/cache'
export async function deletePostAction(postId: string) {
await deletePost(postId) // Auth + authz happen inside the DAL
revalidatePath('/posts')
}
```
> **Good to know:** You can use `import 'server-only'` in both the Data Access Layer and the `"use server"` file itself. Both work when the action is imported into a Client Component (for example, to pass it to `useActionState`), because `"use server"` modules are resolved in a server-only webpack layer.
### Controlling return values
Server Action return values are serialized and sent to the client. Only return what the UI needs, not raw database records.
```tsx filename="app/actions.ts"
'use server'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
// 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')
}
return db.user.update({
where: { id: session.user.id },
data: { name: data.get('name') as string },
})
}
// GOOD: Returns only what the client needs.
export async function updateUserSafe(data: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
await db.user.update({
where: { id: session.user.id },
data: { name: data.get('name') as string },
})
return { success: true }
}
```
### Rate limiting
For expensive operations (sending emails, writing to a database), consider adding rate limiting to prevent abuse. See the [Rate limiting](/docs/app/guides/backend-for-frontend#rate-limiting) example in the Backend for Frontend guide.
### Closures and encryption ### Closures and encryption
Defining a Server Action inside a component creates a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) where the action has access to the outer function's scope. For example, the `publish` action has access to the `publishVersion` variable: Defining a Server Action inside a component creates a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) where the action has access to the outer function's scope. For example, the `publish` action has access to the `publishVersion` variable:
...@@ -473,6 +595,6 @@ If you're doing an audit of a Next.js project, here are a few things we recommen ...@@ -473,6 +595,6 @@ If you're doing an audit of a Next.js project, here are a few things we recommen
- **Data Access Layer:** Is there an established practice for an isolated Data Access Layer? Verify that database packages and environment variables are not imported outside the Data Access Layer. - **Data Access Layer:** Is there an established practice for an isolated Data Access Layer? Verify that database packages and environment variables are not imported outside the Data Access Layer.
- **`"use client"` files:** Are the Component props expecting private data? Are the type signatures overly broad? - **`"use client"` files:** Are the Component props expecting private data? Are the type signatures overly broad?
- **`"use server"` files:** Are the Action arguments validated in the action or inside the Data Access Layer? Is the user re-authorized inside the action? - **`"use server"` files:** Are the Action arguments validated in the action or inside the Data Access Layer? Is the user re-authorized inside the action? Does the action check ownership of the resource (authorization, not just authentication)? Are return values filtered to only what the client needs? Is database access delegated to a `server-only` Data Access Layer?
- **`/[param]/.`** Folders with brackets are user input. Are params validated? - **`/[param]/.`** Folders with brackets are user input. Are params validated?
- **`proxy.ts` and `route.ts`:** Have a lot of power. Spend extra time auditing these using traditional techniques. Perform Penetration Testing or Vulnerability Scanning regularly or in alignment with your team's software development lifecycle. - **`proxy.ts` and `route.ts`:** Have a lot of power. Spend extra time auditing these using traditional techniques. Perform Penetration Testing or Vulnerability Scanning regularly or in alignment with your team's software development lifecycle.
...@@ -6,6 +6,9 @@ description: Learn how to create forms in Next.js with React Server Actions. ...@@ -6,6 +6,9 @@ description: Learn how to create forms in Next.js with React Server Actions.
React Server Actions are [Server Functions](https://react.dev/reference/rsc/server-functions) that execute on the server. They can be called in Server and Client Components to handle form submissions. This guide will walk you through how to create forms in Next.js with Server Actions. React Server Actions are [Server Functions](https://react.dev/reference/rsc/server-functions) that execute on the server. They can be called in Server and Client Components to handle form submissions. This guide will walk you through how to create forms in Next.js with Server Actions.
> [!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.
## How it works ## 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. 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.
...@@ -13,10 +16,17 @@ React extends the HTML [`<form>`](https://developer.mozilla.org/docs/Web/HTML/El ...@@ -13,10 +16,17 @@ React extends the HTML [`<form>`](https://developer.mozilla.org/docs/Web/HTML/El
When used in a form, the function automatically receives the [`FormData`](https://developer.mozilla.org/docs/Web/API/FormData/FormData) object. You can then extract the data using the native [`FormData` methods](https://developer.mozilla.org/en-US/docs/Web/API/FormData#instance_methods): When used in a form, the function automatically receives the [`FormData`](https://developer.mozilla.org/docs/Web/API/FormData/FormData) object. You can then extract the data using the native [`FormData` methods](https://developer.mozilla.org/en-US/docs/Web/API/FormData#instance_methods):
```tsx filename="app/invoices/page.tsx" switcher ```tsx filename="app/invoices/page.tsx" switcher
import { auth } from '@/lib/auth'
export default function Page() { export default function Page() {
async function createInvoice(formData: FormData) { async function createInvoice(formData: FormData) {
'use server' 'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const rawFormData = { const rawFormData = {
customerId: formData.get('customerId'), customerId: formData.get('customerId'),
amount: formData.get('amount'), amount: formData.get('amount'),
...@@ -32,10 +42,17 @@ export default function Page() { ...@@ -32,10 +42,17 @@ export default function Page() {
``` ```
```jsx filename="app/invoices/page.js" switcher ```jsx filename="app/invoices/page.js" switcher
import { auth } from '@/lib/auth'
export default function Page() { export default function Page() {
async function createInvoice(formData) { async function createInvoice(formData) {
'use server' 'use server'
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const rawFormData = { const rawFormData = {
customerId: formData.get('customerId'), customerId: formData.get('customerId'),
amount: formData.get('amount'), amount: formData.get('amount'),
...@@ -154,7 +171,7 @@ const schema = z.object({ ...@@ -154,7 +171,7 @@ const schema = z.object({
}), }),
}) })
export default async function createsUser(formData) { export default async function createUser(formData) {
const validatedFields = schema.safeParse({ const validatedFields = schema.safeParse({
email: formData.get('email'), email: formData.get('email'),
}) })
......
...@@ -99,7 +99,7 @@ While building your application, we recommend using the following features to en ...@@ -99,7 +99,7 @@ While building your application, we recommend using the following features to en
<AppOnly> <AppOnly>
- **[Tainting](/docs/app/api-reference/config/next-config-js/taint):** Prevent sensitive data from being exposed to the client by tainting data objects and/or specific values. - **[Tainting](/docs/app/api-reference/config/next-config-js/taint):** Prevent sensitive data from being exposed to the client by tainting data objects and/or specific values.
- **[Server Actions](/docs/app/getting-started/mutating-data):** Ensure users are authorized to call Server Actions. Review the recommended [security practices](/blog/security-nextjs-server-components-actions). - **[Server Actions](/docs/app/getting-started/mutating-data):** Verify authentication and authorization inside each action. Do not rely on Proxy or layout or page level checks alone. Move database access to a `server-only` [Data Access Layer](/docs/app/guides/data-security#data-access-layer) and consider [rate limiting](/docs/app/guides/backend-for-frontend#rate-limiting) for expensive operations. Review the recommended [security practices](/blog/security-nextjs-server-components-actions).
</AppOnly> </AppOnly>
......
...@@ -12,20 +12,32 @@ The following example shows a file with a `use server` directive at the top. All ...@@ -12,20 +12,32 @@ The following example shows a file with a `use server` directive at the top. All
```tsx filename="app/actions.ts" highlight={1} switcher ```tsx filename="app/actions.ts" highlight={1} switcher
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
export async function createUser(data: { name: string; email: string }) { export async function createUser(data: { name: string; email: string }) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const user = await db.user.create({ data }) const user = await db.user.create({ data })
return user return { id: user.id, name: user.name }
} }
``` ```
```jsx filename="app/actions.js" highlight={1} switcher ```jsx filename="app/actions.js" highlight={1} switcher
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
export async function createUser(data) { export async function createUser(data) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const user = await db.user.create({ data }) const user = await db.user.create({ data })
return user return { id: user.id, name: user.name }
} }
``` ```
...@@ -38,9 +50,17 @@ Assuming you have a `fetchUsers` Server Function in `actions.ts`: ...@@ -38,9 +50,17 @@ Assuming you have a `fetchUsers` Server Function in `actions.ts`:
```tsx filename="app/actions.ts" highlight={1} switcher ```tsx filename="app/actions.ts" highlight={1} switcher
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
export async function fetchUsers() { export async function fetchUsers() {
const users = await db.user.findMany() const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const users = await db.user.findMany({
select: { id: true, name: true, email: true },
})
return users return users
} }
``` ```
...@@ -48,9 +68,17 @@ export async function fetchUsers() { ...@@ -48,9 +68,17 @@ export async function fetchUsers() {
```jsx filename="app/actions.js" highlight={1} switcher ```jsx filename="app/actions.js" highlight={1} switcher
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { auth } from '@/lib/auth'
export async function fetchUsers() { export async function fetchUsers() {
const users = await db.user.findMany() const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const users = await db.user.findMany({
select: { id: true, name: true, email: true },
})
return users return users
} }
``` ```
...@@ -88,6 +116,7 @@ export default async function PostPage({ params }: { params: { id: string } }) { ...@@ -88,6 +116,7 @@ export default async function PostPage({ params }: { params: { id: string } }) {
async function updatePost(formData: FormData) { async function updatePost(formData: FormData) {
'use server' 'use server'
// Verify auth before saving (e.g. inside savePost)
await savePost(params.id, formData) await savePost(params.id, formData)
revalidatePath(`/posts/${params.id}`) revalidatePath(`/posts/${params.id}`)
} }
...@@ -105,6 +134,7 @@ export default async function PostPage({ params }) { ...@@ -105,6 +134,7 @@ export default async function PostPage({ params }) {
async function updatePost(formData) { async function updatePost(formData) {
'use server' 'use server'
// Verify auth before saving (e.g. inside savePost)
await savePost(params.id, formData) await savePost(params.id, formData)
revalidatePath(`/posts/${params.id}`) revalidatePath(`/posts/${params.id}`)
} }
...@@ -115,28 +145,27 @@ export default async function PostPage({ params }) { ...@@ -115,28 +145,27 @@ export default async function PostPage({ params }) {
## Security considerations ## Security considerations
When using the `use server` directive, it's important to ensure that all server-side logic is secure and that sensitive data remains protected. Design your data access functions as secure primitives: validate inputs, check authentication and authorization, and constrain return types to only what the caller needs. When Server Functions delegate to a [Data Access Layer](/docs/app/guides/data-security#using-a-data-access-layer-for-mutations), these guarantees live in one place and apply consistently.
{/* TODO: showcase input validation */}
### Authentication and authorization ### Authentication and authorization
Always authenticate and authorize users before performing sensitive server-side operations. 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 ```tsx filename="app/actions.ts" highlight={1,7,8,9,10} switcher
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { authenticate } from '@/lib/auth' // Your authentication library import { auth } from '@/lib/auth' // Your authentication library
export async function createUser( export async function createUser(data: { name: string; email: string }) {
data: { name: string; email: string }, const session = await auth()
token: string if (!session?.user) {
) {
const user = authenticate(token)
if (!user) {
throw new Error('Unauthorized') throw new Error('Unauthorized')
} }
const newUser = await db.user.create({ data }) const newUser = await db.user.create({ data })
return newUser return { id: newUser.id, name: newUser.name }
} }
``` ```
...@@ -144,18 +173,22 @@ export async function createUser( ...@@ -144,18 +173,22 @@ export async function createUser(
'use server' 'use server'
import { db } from '@/lib/db' // Your database client import { db } from '@/lib/db' // Your database client
import { authenticate } from '@/lib/auth' // Your authentication library import { auth } from '@/lib/auth' // Your authentication library
export async function createUser(data, token) { export async function createUser(data) {
const user = authenticate(token) const session = await auth()
if (!user) { if (!session?.user) {
throw new Error('Unauthorized') throw new Error('Unauthorized')
} }
const newUser = await db.user.create({ data }) const newUser = await db.user.create({ data })
return newUser return { id: newUser.id, name: newUser.name }
} }
``` ```
### Return values
Server Function return values are serialized and sent to the client. Only return data the UI needs, not raw database records. See the [Data Security guide](/docs/app/guides/data-security#controlling-return-values) for more details.
## Reference ## Reference
See the [React documentation](https://react.dev/reference/rsc/use-server) for more information on `use server`. See the [React documentation](https://react.dev/reference/rsc/use-server) for more information on `use server`.
...@@ -210,6 +210,10 @@ Proxy will be invoked for **every route in your project**. Given this, it's cruc ...@@ -210,6 +210,10 @@ Proxy will be invoked for **every route in your project**. Given this, it's cruc
7. Dynamic Routes (`/blog/[slug]`) 7. Dynamic Routes (`/blog/[slug]`)
8. `fallback` (`rewrites`) from `next.config.js` 8. `fallback` (`rewrites`) from `next.config.js`
> **Good to know:** [Server Functions](/docs/app/api-reference/directives/use-server) are not separate routes in this chain. They are handled as POST requests to the route where they are used, so a Proxy matcher that excludes a path will also skip Server Function calls on that path.
>
> A matcher change or a refactor that moves a Server Function to a different route can silently remove Proxy coverage. Always verify authentication and authorization inside each Server Function rather than relying on Proxy alone. See the [Data Security guide](/docs/app/guides/data-security#authentication-and-authorization) for recommended patterns.
## Runtime ## Runtime
Proxy defaults to using the Node.js runtime. The [`runtime`](/docs/app/api-reference/file-conventions/route-segment-config#runtime) config option is not available in Proxy files. Setting the `runtime` config option in Proxy will throw an error. Proxy defaults to using the Node.js runtime. The [`runtime`](/docs/app/api-reference/file-conventions/route-segment-config#runtime) config option is not available in Proxy files. Setting the `runtime` config option in Proxy will throw an error.
......
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