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

Next.js App Router点击按钮设置Cookie的问题求助

问题根源

  • App Router 中默认组件是Server 组件,这类组件运行在服务器端,无法添加 onClick 这类浏览器端交互事件,所以第一次报错提示需要转为 Client 组件。
  • 但 next/headers 里的 cookies 对象是仅支持在 Server 组件/Server Action 中使用的 API,当你给组件加上 'use client' 转为 Client 组件后,就不能再导入使用它,因此出现第二次报错。

直接在 Client 组件里使用浏览器自带的 document.cookie 设置 Cookie,无需依赖 Server 端 API,适合简单场景:

'use client'; // 标记为 Client 组件
import Image from "next/image";
import styles from "./page.module.css";

export default function Home() {
  function setCookie() {
    // 示例:设置名为 testCookie、值为 hello 的 Cookie,有效期1天
    document.cookie = "testCookie=hello; max-age=86400; path=/";
  }

  return (
   <div>
      <div>hello</div>
      <button onClick={setCookie}>设置 Cookie</button>
    </div>
  );
}

如果需要设置 HttpOnly、Secure 这类只能由 Server 端配置的 Cookie 属性,可使用 Server Action:

  1. 定义带 'use server' 标记的 Server Action,在其中使用 next/headers 的 cookies API。
  2. 在 Client 组件中调用这个 Server Action。

主页面代码(page.js)

import Image from "next/image";
import styles from "./page.module.css";
import SetCookieButton from "./SetCookieButton";

export default function Home() {
  return (
   <div>
      <div>hello</div>
      <SetCookieButton />
    </div>
  );
}

按钮子组件代码(SetCookieButton.jsx)

'use client'; // 标记为 Client 组件

// 定义 Server Action
async function setCookieAction() {
  'use server';
  const { cookies } = require('next/headers');
  cookies().set('testCookie', 'hello-from-server', {
    maxAge: 86400,
    path: '/',
    httpOnly: true, // 仅 Server 端可读取,提升安全性
    secure: process.env.NODE_ENV === 'production' // 生产环境下启用HTTPS传输
  });
}

export default function SetCookieButton() {
  return (
    <button onClick={setCookieAction}>通过 Server Action 设置 Cookie</button>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:27:24