Next.js Server Actions 与缓存实践
MrSmy Lv5

Next.js 14 把 Server Actions 转成稳定特性,带来的变化挺大:表单可以不用写接口、不用 fetch、不用维护 loading 状态,直接调一个服务端函数。方便的同时,安全边界也变得模糊——函数是公开的 HTTP 端点,只是调用方式被隐藏了。这篇整理实际用法和必须注意的点。

基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// app/posts/new/page.tsx
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { db } from '@/lib/db'

async function createPost(formData: FormData) {
'use server'

const title = String(formData.get('title') ?? '').trim()
const content = String(formData.get('content') ?? '').trim()

if (!title || title.length > 100) {
throw new Error('标题不合法')
}

await db.post.create({ data: { title, content } })
revalidatePath('/posts')
redirect('/posts')
}

export default function NewPostPage() {
return (
<form action={createPost}>
<input name="title" required />
<textarea name="content" required />
<button type="submit">发布</button>
</form>
)
}

'use server' 加在函数体内,这个函数就只能在服务端执行。表单提交时浏览器会自动发一个 POST 到当前路由,Next 负责把 FormData 传过去。

即使 JavaScript 被禁用,表单也能提交——这是渐进增强带来的真实收益。

独立文件组织

把 action 抽到单独文件,才能被客户端组件复用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// app/actions/post.ts
'use server'

import { revalidatePath } from 'next/cache'
import { z } from 'zod'
import { db } from '@/lib/db'
import { getSession } from '@/lib/auth'

const schema = z.object({
title: z.string().min(1).max(100),
content: z.string().min(1)
})

export async function updatePost(id: string, input: unknown) {
// 1. 认证
const session = await getSession()
if (!session) throw new Error('UNAUTHORIZED')

// 2. 校验
const data = schema.parse(input)

// 3. 鉴权:这个人能不能改这条数据
const post = await db.post.findUnique({ where: { id } })
if (!post || post.authorId !== session.userId) throw new Error('FORBIDDEN')

// 4. 写入
await db.post.update({ where: { id }, data })

// 5. 失效缓存
revalidatePath(`/posts/${id}`)
revalidatePath('/posts')

return { ok: true }
}

这五步一个都不能省。Server Action 等于一个公开的 POST 接口,客户端可以构造任意参数调用它,它不会因为”UI 上没有这个按钮”而拒绝调用。把 use client 组件里的调用当成普通 API 请求对待,是最重要的心理模型。

表单状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'use client'

import { useFormState, useFormStatus } from 'react-dom'
import { createPost } from '@/app/actions/post'

function SubmitButton() {
const { pending } = useFormStatus()
return (
<button type="submit" disabled={pending}>
{pending ? '提交中...' : '提交'}
</button>
)
}

export default function Form() {
const [state, formAction] = useFormState(async (prev: any, formData: FormData) => {
const result = await createPost(formData)
return result?.ok ? { ok: true } : { error: result?.message }
}, {})

return (
<form action={formAction}>
<input name="title" />
{state?.error && <p className="error">{state.error}</p>}
<SubmitButton />
</form>
)
}

useFormStatus 必须在 form 的子组件里用,直接在 form 所在组件用拿不到 pending。这个限制让很多人踩坑。

useFormState 后来在 React 19 里改名为 useActionState,签名一致但 import 从 react 而不是 react-dom。

乐观更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
'use client'

import { useOptimistic } from 'react'
import { toggleLike } from '@/app/actions/like'

export function LikeButton({ postId, liked, count }: { postId: string; liked: boolean; count: number }) {
const [optimistic, addOptimistic] = useOptimistic(
{ liked, count },
(state, next: boolean) => ({
liked: next,
count: state.count + (next ? 1 : -1)
})
)

return (
<button
onClick={() => {
addOptimistic(!optimistic.liked)
toggleLike(postId, !optimistic.liked)
}}
>
{optimistic.liked ? '已赞' : '点赞'} {optimistic.count}
</button>
)
}

useOptimistic 的特点是”失败自动回滚”:action 抛错或组件重新渲染后,状态会回到服务端的真实值。它比自己手写 setState + 回滚干净得多。

缓存与失效

Next 14 的缓存有四个层面,混在一起最容易出错:

层面 控制方式
fetch 数据缓存 fetch(url, { cache: 'no-store' }) / next.revalidate
路由段静态化 export const dynamic = 'force-dynamic'
全路由缓存 客户端导航时的 RSC payload 缓存
数据层缓存 unstable_cache / cache()

写完数据后要让人看到变化,通常得同时做两件事:

1
2
3
4
import { revalidatePath, revalidateTag } from 'next/cache'

revalidatePath('/posts') // 让这个路径的缓存失效
revalidateTag('posts') // 让带这个 tag 的 fetch 缓存失效

更推荐 tag 的方式,它和路径解耦:

1
2
3
const posts = await fetch(url, { next: { tags: ['posts'] } })
// 写入后
revalidateTag('posts')

revalidatePath 在动态路由场景容易漏,比如改了文章详情,却忘了失效列表页和首页。

常见坑

1. 在客户端组件里误用 'use server'

'use server' 文件里的导出必须是 async 函数,不能导对象、常量。写错会出现很抽象的编译错误。

2. action 里拿不到 request

Server Action 没有 req 参数。需要 header、cookie 时用 next/headers:

1
2
import { cookies, headers } from 'next/headers'
const token = cookies().get('token')?.value

3. 直接传函数给客户端组件不行

Server Action 可以作为 prop 传给客户端组件(Next 会做引用序列化),但普通服务端函数不行。

4. 不校验就相信参数

1
2
3
4
5
// 危险:客户端能传任意 id
export async function deletePost(id: string) {
'use server'
await db.post.delete({ where: { id } })
}

这行代码等价于”任何人都能删除任意文章”。所有 action 都要在服务端做身份 + 权限校验,不能依赖前端有没有传某个字段。

5. 长耗时任务阻塞渲染

action 是同步等待的,里面跑 30 秒的任务会让表单一直 pending。耗时操作应该丢到队列里,action 只负责入队并返回。

小结

Server Actions 让”表单 + 数据写入”这条链路短了很多,代价是把”接口”这个概念藏起来了。它没有降低安全要求,只是把安全责任从”路由层”挪到了”函数内部”。写的时候保持一个习惯就够了:每个 action 的第一行都是身份校验。

  • 本文标题:Next.js Server Actions 与缓存实践
  • 本文作者:MrSmy
  • 创建时间:2024-07-21 15:58:00
  • 本文链接:https://fengyang.live/2024/07/21/Next.js Server Actions与缓存实践/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!