Next.js App Router点击按钮设置Cookie的问题求助
问题根源
- App Router 中默认组件是Server 组件,这类组件运行在服务器端,无法添加
onClick这类浏览器端交互事件,所以第一次报错提示需要转为 Client 组件。 - 但
next/headers里的cookies对象是仅支持在 Server 组件/Server Action 中使用的 API,当你给组件加上'use client'转为 Client 组件后,就不能再导入使用它,因此出现第二次报错。
解决方法一:Client 组件中用浏览器原生 API 设置 Cookie
直接在 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> ); }
解决方法二:用 Server Action 在 Server 端设置 Cookie
如果需要设置 HttpOnly、Secure 这类只能由 Server 端配置的 Cookie 属性,可使用 Server Action:
- 定义带
'use server'标记的 Server Action,在其中使用next/headers的cookiesAPI。 - 在 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
相关产品推荐
相关产品推荐

