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

如何在NextJS的_document.js中获取Cookie以动态切换主题?

在Next.js的_document.js中通过Cookie动态设置主题类名

要实现通过Cookie动态给body分配className切换主题,你可以在_document.js的服务端逻辑里解析请求头中的Cookie,把主题值传递给组件后动态渲染类名,完整代码如下:

import NextDocument, { Html, Head, Main, NextScript } from 'next/document'

// 解析Cookie字符串为键值对对象
const parseCookie = (cookie) => {
  if (!cookie) return {}
  return cookie.split(';').reduce((acc, item) => {
    const [key, value] = item.trim().split('=')
    acc[key] = value
    return acc
  }, {})
}

function Document(props) {
  // 从props获取主题值,默认设为lightMode
  const theme = props.theme || 'lightMode'
  return (
    <Html lang="en">
      <Head />
      {/* 动态拼接body的className */}
      <body className={`bgimg ${theme}`}>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

Document.getInitialProps = async (ctx) => {
  const initialProps = await NextDocument.getInitialProps(ctx)
  // 从服务端请求头中获取Cookie并解析
  const cookies = parseCookie(ctx.req?.headers.cookie)
  // 提取Cookie中的theme字段,没有则用默认值
  const theme = cookies.theme || 'lightMode'
  
  return { ...initialProps, theme }
}

export default Document

关键说明

  • parseCookie工具函数负责把Cookie字符串转换成便于读取的键值对对象
  • 服务端渲染时,ctx.req.headers.cookie能拿到请求携带的所有Cookie,前端浏览器环境下不需要这里的逻辑(因为_document只在服务端执行)
  • 把解析出的主题值作为props传给Document组件,就能动态生成body的className,实现主题的服务端初始化渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:52:41