You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13.5 Server Action中设置Cookie后重定向失效问题求助

在Next.js 13.5实验性Server Action中设置Cookie后重定向的问题

我在Next.js 13.5的实验性Server Action中尝试设置名为login的Cookie,随后将用户重定向至首页。移除重定向操作时,服务器会在响应头中正常返回set-cookie: login=true;但设置Cookie后立即执行redirect时,Cookie不会被写入响应头,用户直接被重定向。请问这是操作错误还是非预期行为?

代码示例

// page.js
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation'; // 补充必要的导入

export default function Page() {

  async function checkPassword(formData) {   
    'use server'

    const password = formData.get('pass')

    if (process.env.PASSWORD_PROTECT === password) {
        cookies().set('login' , "true");
        redirect('/')
    } else {
        redirect('/password')
    }
  }

  return (
    <div className="container">
      <div className="grid place-content-center min-h-screen">
        <div className="flex flex-col items-center gap-4">
          <h1 className="text-2xl">This Page is Under Development... </h1>
          <p>Enter Password:</p>
          <form action={checkPassword} method="POST">
            <div className="form-control">
              <div className="input-group">
                <input
                  type="text"
                  name="pass"
                  className="input input-bordered"
                />
                <button className="btn" type="submit">Login</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

问题分析与解决

这并非操作错误,而是Next.js 13.5早期版本实验性Server Action的非预期bug——设计上cookies().set()与redirect()理应协同工作,重定向响应头需包含Set-Cookie字段,但早期版本中存在执行顺序问题,导致Cookie设置被跳过。

解决办法:

  1. 升级Next.js版本:该bug在13.5.3及后续稳定版中已修复,直接升级即可解决问题。
  2. 临时替代方案(无法升级时):
    • 手动在redirect的响应头中添加Cookie(推荐,更可靠):
      cookies().set('login', "true");
      redirect('/', {
        headers: {
          'Set-Cookie': 'login=true; Path=/; HttpOnly; SameSite=Lax'
        }
      });
      
    • 或添加微小延迟再执行重定向(仅临时应急):
      cookies().set('login', "true");
      await new Promise(resolve => setTimeout(resolve, 10));
      redirect('/');
      

注意事项

确保代码已正确导入cookies和redirect函数,这是Server Action正常运行的前提。

内容的提问来源于stack exchange,提问作者talisker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:30:10