NNext.js 中文网 GitHub

use server

了解如何使用 use server 指令在服务端执行代码。

use server 指令用于指定某个函数或文件在服务端执行。它可以放在文件顶部,表示文件中的所有函数都在服务端运行;也可以内联放在函数顶部,将该函数标记为 Server Function。这是 React 的一项特性。

有关 Next.js 特有的 Server Action 行为(响应模型、安全性、配置、部署),请参阅 Server Actions 与数据变更。

小知识:Proxy 不会应用指令转换,因此 use server 在 Proxy 中无效。在你的应用中其他地方属于 Server Function 的函数,在 Proxy 导入它时会作为普通函数运行。

在文件顶部使用 use server#

以下示例展示了一个顶部带有 use server 指令的文件。文件中的所有函数都在服务端执行。

app/actions.ts
'use server'
import { db } from '@/lib/db' // 你的数据库客户端
import { auth } from '@/lib/auth'

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 })
  return { id: user.id, name: user.name }
}
app/actions.js
'use server'
import { db } from '@/lib/db' // 你的数据库客户端
import { auth } from '@/lib/auth'

export async function createUser(data) {
  const session = await auth()
  if (!session?.user) {
    throw new Error('Unauthorized')
  }

  const user = await db.user.create({ data })
  return { id: user.id, name: user.name }
}

在 Client Component 中使用 Server Function#

要在 Client Component 中使用 Server Function,你需要在一个专门的文件中创建 Server Function,并在文件顶部使用 use server 指令。然后,这些 Server Function 就可以被导入到 Client Component 和 Server Component 中执行。

假设你在 actions.ts 中有一个 fetchUsers Server Function:

app/actions.ts
'use server'
import { db } from '@/lib/db' // 你的数据库客户端
import { auth } from '@/lib/auth'

export async function fetchUsers() {
  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
}
app/actions.js
'use server'
import { db } from '@/lib/db' // 你的数据库客户端
import { auth } from '@/lib/auth'

export async function fetchUsers() {
  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
}

然后,你可以将 fetchUsers Server Function 导入到 Client Component 中,并在客户端执行它。

app/components/my-button.tsx
'use client'
import { fetchUsers } from '../actions'

export default function MyButton() {
  return <button onClick={() => fetchUsers()}>Fetch Users</button>
}
app/components/my-button.js
'use client'
import { fetchUsers } from '../actions'

export default function MyButton() {
  return <button onClick={() => fetchUsers()}>Fetch Users</button>
}

内联使用 use server#

在以下示例中,use server 内联用在函数顶部,将其标记为 Server Function:

app/posts/[id]/page.tsx
import { EditPost } from './edit-post'
import { revalidatePath } from 'next/cache'

export default async function PostPage({ params }: PageProps<'/posts/[id]'>) {
  const { id } = await params
  const post = await getPost(id)

  async function updatePost(formData: FormData) {
    'use server'
    // 保存前先验证身份(例如在 savePost 内部)
    await savePost(id, formData)
    revalidatePath(`/posts/${id}`)
  }

  return <EditPost updatePostAction={updatePost} post={post} />
}
app/posts/[id]/page.js
import { EditPost } from './edit-post'
import { revalidatePath } from 'next/cache'

export default async function PostPage({ params }) {
  const { id } = await params
  const post = await getPost(id)

  async function updatePost(formData) {
    'use server'
    // 保存前先验证身份(例如在 savePost 内部)
    await savePost(id, formData)
    revalidatePath(`/posts/${id}`)
  }

  return <EditPost updatePostAction={updatePost} post={post} />
}

安全注意事项#

将数据访问函数设计为安全的原语:验证输入、检查身份验证与授权,并将返回类型限制为调用方所需的内容。当 Server Function 委托给数据访问层时,这些保障集中在一处并一致地生效。

身份验证与授权#

在执行敏感的服务端操作之前,务必对用户进行身份验证和授权。应从 cookies 或 headers 中读取认证信息,而不是将令牌作为函数参数接收。

app/actions.ts
'use server'

import { db } from '@/lib/db' // 你的数据库客户端
import { auth } from '@/lib/auth' // 你的认证库

export async function createUser(data: { name: string; email: string }) {
  const session = await auth()
  if (!session?.user) {
    throw new Error('Unauthorized')
  }
  const newUser = await db.user.create({ data })
  return { id: newUser.id, name: newUser.name }
}
app/actions.js
'use server'

import { db } from '@/lib/db' // 你的数据库客户端
import { auth } from '@/lib/auth' // 你的认证库

export async function createUser(data) {
  const session = await auth()
  if (!session?.user) {
    throw new Error('Unauthorized')
  }
  const newUser = await db.user.create({ data })
  return { id: newUser.id, name: newUser.name }
}

返回值#

Server Function 的返回值会被序列化并发送到客户端。只返回 UI 所需的数据,不要返回原始数据库记录。有关更多细节,请参阅数据安全指南。

参考#

有关 use server 的更多信息,请参阅 React 文档。

Next.js 中文网