【问题标题】:Access cookies on the "server" with a statically generated Next.js site?使用静态生成的 Next.js 站点访问“服务器”上的 cookie?
【发布时间】:2022-08-16 13:50:08
【问题描述】:

我使用 getStaticProps() 创建了一个使用 Next.js 静态生成的网站。在网站上有一个按钮,您可以在其中切换三个不同的主题(图片右下方)。

这作为例外工作,但现在我想在每个会话之间坚持这个,并在页面加载时应用正确的主题。我知道我可以做这个客户端,但这会导致网站总是从白色闪烁到选定的颜色,这不好。

有没有办法解决这个问题?我不想将网站转换为服务器渲染,只是为了启用此功能。也许与边缘工作者、新的中间件等有关?我不知道。 ???

标签: cookies next.js


【解决方案1】:

从技术上讲,它不能完成,并且已经在这里问过:

How to read cookies in getStaticProps and getStaticPaths in Next.js

getStaticProps 是在构建时,所以没有 cookie 的概念。

然而 :)

我在想也许有一个你可以使用的黑客。没试过,但应该可以:

您可以使用 Next.js redirects(或 rewritesbased on the cookie value,重定向到 3 个主题之一中的预构建页面。

因此,如果您在 cookie 中检测到“theme=blue”,您可以将页面重写为 /blueIndex.js:

module.exports = {
  async rewrites() {
    return [
        {
        source: '/',
        has: [
          {
            type: 'cookie',
            key: 'theme',
            value: 'blue',
          },
        ],
        permanent: true,
        destination: '/blueIndex.js',
      },
    ]
  },
}

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 2021-01-20
    • 2020-05-28
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多