test opus

zk
zk
··7

What Are Server Functions?

Basic Concepts

Server Functions are asynchronous functions that run on the server side. Since clients need to invoke them via network requests, these functions must be asynchronous. This design allows client-side code to interact with the server just like calling ordinary async functions, without manually writing API routes or dealing with complex network communication logic.

When used in the context of actions or mutations, they are also referred to as Server Actions.


Server Actions

Definition and Conventions

By convention, Server Actions are asynchronous functions used in conjunction with startTransition. startTransition is a React API that marks certain updates as "non-urgent transitions," preventing them from blocking UI rendering.

startTransition is triggered automatically in the following cases, with no need for manual invocation:

  • When passed to a <form> element via the action prop
  • When passed to a <button> element via the formAction prop

Usage Example

// Define a server function
'use server'

async function submitForm(formData) {
  const name = formData.get('name')
  // Process data on the server, e.g., write to a database
  await db.user.create({ data: { name } })
}

// Use it in a client component
export default function MyForm() {
  return (
    // Pass the server function directly to the action prop
    <form action={submitForm}>
      <input type="text" name="name" placeholder="Enter your name" />
      {/* Pass the server function to the formAction prop */}
      <button type="submit" formAction={submitForm}>
        Submit
      </button>
    </form>
  )
}

How It Works

Single Round-Trip Optimization

When an Action is triggered, Next.js can accomplish all of the following within a single server round trip:

  • ✅ Execute server-side logic (e.g., database operations, file processing)
  • ✅ Return the updated UI
  • ✅ Deliver the latest data state

This mechanism significantly reduces the number of network requests, offering superior performance compared to the traditional "request → response → fetch data again" pattern.

Traditional pattern:
Client → [Submit request] → Server → [Return result] → Client → [Fetch data again] → Server → [Return data] → Client

Server Actions pattern:
Client → [POST request] → Server → [Return updated UI + latest data] → Client

Underlying HTTP Implementation

Under the hood, Server Actions use the HTTP POST method — and only POST can trigger a call. This design aligns with HTTP semantic conventions:

HTTP MethodSemanticsCan Trigger Server Actions
GETRead / query data❌ Not supported
POSTSubmit / modify data✅ Supported
PUTUpdate data❌ Not supported
DELETEDelete data❌ Not supported

💡 Why only POST? Semantically, a POST request means "submit data and produce side effects," which closely aligns with the nature of Server Actions (performing data mutation operations). Additionally, POST request bodies can safely carry form data, whereas GET request parameters are exposed in the URL — making GET unsuitable for transmitting sensitive information or large volumes of data.


Summary of Key Advantages

FeatureDescription
Simplified DevelopmentNo need to manually create API routes — invoke server logic directly within components
Type SafetySupports end-to-end TypeScript type inference
Performance OptimizationData submission and UI updates completed in a single round trip
安全性服务器端代码不会暴露给客户端

登录 后可以点赞

评论

登录 后可以发表评论

暂无评论,快来抢沙发吧