NextJS 13.4.1服务端操作设置Cookie报错:Property 'set'不存在
出现这个错误的核心原因是:Server Action的调用上下文决定了cookies()返回的对象类型。当你的Server Action在GET请求上下文(比如客户端组件的useEffect、普通点击事件直接调用)中执行时,cookies()返回的是只读的ReadonlyRequestCookies,自然没有set方法;只有在POST请求的上下文中触发Server Action,才能获得可写的Cookie对象。
正确的解决方案
1. 通过表单POST触发Server Action(推荐方式)
将Server Action绑定到表单的action属性,提交表单时会以POST请求触发,此时cookies()返回可写的ResponseCookies:
import { cookies } from 'next/headers'; import { redirect } from 'next/navigation'; export default function UserForm() { async function create(formData) { 'use server'; // 此时可正常调用set方法 cookies().set({ name: 'name', value: 'lee', httpOnly: true, path: '/', secure: process.env.NODE_ENV === 'production', }); redirect('/'); } return ( <form action={create}> {/* 表单内容 */} <button type="submit">提交</button> </form> ); }
2. 手动通过Response设置Cookie(兼容场景)
如果需要在非表单POST的场景下设置Cookie,可以直接通过Response对象的Set-Cookie头实现:
import { redirect } from 'next/navigation'; async function create(data) { 'use server'; const cookieValue = 'name=lee; HttpOnly; Path=/; ' + (process.env.NODE_ENV === 'production' ? 'Secure;' : ''); const response = new Response(null, { status: 302, headers: { 'Set-Cookie': cookieValue, Location: '/', }, }); redirect('/', response); }
3. 升级Next.js版本
13.4.1存在部分类型定义的小问题,升级到13.4.x的最新补丁版本(比如13.4.19+),可以修复一些类型推断的异常,但核心解决思路还是确保Server Action在POST上下文执行。
内容的提问来源于stack exchange,提问作者Tubagus Saifulloh
相关产品推荐
相关产品推荐

