use server
use server 指令將函式或檔案指定為在伺服器端執行。它可以用於檔案頂部,以表明檔案中所有函式都是伺服器端函式;也可以在函式頂部內聯使用,以將函式標記為伺服器函式。這是 React 的一個功能。
在檔案頂部使用 use server
以下示例展示了一個檔案,其頂部帶有 use server 指令。檔案中的所有函式都在伺服器上執行。
app/actions.ts
'use server'
import { db } from '@/lib/db' // Your database client
export async function createUser(data: { name: string; email: string }) {
const user = await db.user.create({ data })
return user
}在客戶端元件中使用伺服器函式
要在客戶端元件中使用伺服器函式,您需要在一個專用檔案中建立伺服器函式,並在檔案頂部使用 use server 指令。然後,這些伺服器函式可以被匯入到客戶端和伺服器元件中並執行。
假設您在 actions.ts 中有一個 fetchUsers 伺服器函式
app/actions.ts
'use server'
import { db } from '@/lib/db' // Your database client
export async function fetchUsers() {
const users = await db.user.findMany()
return users
}然後您可以將 fetchUsers 伺服器函式匯入到客戶端元件中並在客戶端執行。
app/components/my-button.tsx
'use client'
import { fetchUsers } from '../actions'
export default function MyButton() {
return <button onClick={() => fetchUsers()}>Fetch Users</button>
}內聯使用 use server
在以下示例中,use server 在函式頂部內聯使用,以將其標記為伺服器函式
app/posts/[id]/page.tsx
import { EditPost } from './edit-post'
import { revalidatePath } from 'next/cache'
export default async function PostPage({ params }: { params: { id: string } }) {
const post = await getPost(params.id)
async function updatePost(formData: FormData) {
'use server'
await savePost(params.id, formData)
revalidatePath(`/posts/${params.id}`)
}
return <EditPost updatePostAction={updatePost} post={post} />
}安全注意事項
使用 use server 指令時,確保所有伺服器端邏輯都是安全的,並且敏感資料受到保護至關重要。
認證與授權
在執行敏感的伺服器端操作之前,務必進行使用者認證和授權。
app/actions.ts
'use server'
import { db } from '@/lib/db' // Your database client
import { authenticate } from '@/lib/auth' // Your authentication library
export async function createUser(
data: { name: string; email: string },
token: string
) {
const user = authenticate(token)
if (!user) {
throw new Error('Unauthorized')
}
const newUser = await db.user.create({ data })
return newUser
}參考
有關 use server 的更多資訊,請參閱 React 文件。
這有幫助嗎?