Next.js Server Actions 是如何用 HTTP 实现 RPC 的?
🧠 背景
在传统前端中,我们通过 fetch('/api/xxx') 或 axios.post(...) 与后端通信,采用的是显式的 HTTP 请求调用。
但从 Next.js App Router 开始,我们有了一个全新的通信方式 —— Server Actions。
Server Action 看起来只是一个异步函数:
async function updateName(formData: FormData) { 'use server' ... }
但实际上,它是一种 HTTP RPC 函数调用模型,Next.js 在背后自动帮我们:
- 注册服务端处理器
- 生成调用 ID
- 提供客户端 proxy
- 通过 HTTP 完成远程调用
### 🧩 一句话理解 | TL;DR
✅ Next.js Server Actions 是一种用 HTTP POST 模拟函数调用的轻量 RPC 协议。
✅ Next.js Server Actions are a lightweight RPC mechanism implemented via HTTP POST.
编译阶段生成代理 | Compile-Time Proxy Generation
Next.js 编译器会:
-
为函数生成唯一的 ID,如 ACTION/abc123
-
生成对应 handler 文件 .next/server/app/ACTION/abc123.js,内容大致如下:
Next.js compiler will:
Generate a unique ID like ACTION/abc123
Create a handler file like .next/server/app/ACTION/abc123.js containing:
import { updateName } from '../../../../app/page';
export default async function handler(req) {
const formData = await req.formData();
return await updateName(formData);
}
- 客户端拿到代理函数 | Client Receives a Proxy Function
拿到的并不是原来的Action,而是一个Proxy对象!
{
$$typeof: Symbol(server_action),
id: '__ACTION__/abc123',
bound: []
}
当客户端点击事件
1.表单触发请求 | Form Triggers RPC Call
点击提交后,浏览器发送一个 POST 请求:
When the form is submitted, the browser sends a POST request:
POST /__ACTION__/abc123
Content-Type: multipart/form-data
name=NewName
2.服务端 handler 匹配并执行原函数 | Server Dispatches to Real Function
服务端路由匹配到 /ACTION/abc123
Next.js 调用编译生成的 handler
handler 内部再调用 updateName(formData)
The server routes the request to /ACTION/abc123
Next.js executes the compiled handler
The handler then invokes updateName(formData)
🚀 为什么这是一种 RPC?| Why Is This Considered RPC?
✅ 调用的是函数,不是 URL
✅ 自动绑定参数、执行、响应
✅ 无须手动写路由或 fetch
✅ 像调用本地函数一样使用服务端逻辑
✅ You call a function, not a URL
✅ Parameters, execution, and response are handled automatically
✅ No need to write routes or fetch calls manually
✅ Looks like a local function call but runs on the server
📚 总结 | Conclusion
Server Actions 是 RSC 世界下最接近“函数即服务(Function as Resource)”的架构模型。
Server Actions represent the most direct form of function-as-resource architecture in the RSC ecosystem.
它优雅地用 HTTP 实现了轻量级 RPC 调用,并融合在 React 组件层级里。
This elegantly embeds RPC over HTTP inside the component hierarchy of React.
Server Actions 正在重新定义我们对“前端调用服务”的理解 —— 让组件之间的“逻辑跳跃”变成了“函数调用”。
Server Actions are redefining how frontend calls backend — turning network jumps into seamless function calls.
这正是前后端融合的开始,也是全栈工程师时代的技术演进。
This marks the beginning of frontend-backend convergence — a milestone in the evolution of full-stack engineering.

浙公网安备 33010602011771号