如何在 Next.js 中读取 getStaticProps 和 getStaticPaths 中的 cookie

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

我无法读取 getStaticPathsgetStaticProps 中的 cookie,在 SSR 中,我可以请求带有上下文的 cookie,但即使使用 js-cookie, cookie-cutter, cookies 等包,我也无法读取设置了cookies,导致无法获取数据。

这是我要获取的token,为了开发我去掉了httpOnly

export async function getStaticPaths(){
    const data = await callApi("/jobs", "GET", token)

    const paths = data.map(jobs => ({
        params: {slug: jobs.slug}
    }))
    return{
        paths,
        fallback: true,
    }
}

这是 getStaticPaths。

getStaticPathsgetStaticProps 都是 运行 在服务器 (node.js) 上的方法,因此作为浏览器的 cookies API 不可用还

可以在服务器 req.cookiesreq.headers.cookie 和客户端 document.cookie 上访问 Cookie。但与 getServerSideProps 在运行时生成 HTML 不同,getStaticProps 在构建时生成 HTML,因此不知道请求 devise/browser。从 getStaticProps:

发送请求时用户代理的外观可以看出这一点
'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'

此外,还有一个演示应用程序 here 展示了这一切的工作原理。

如果您尝试从 getStaticProps 访问 cookie 的原因是为了身份验证,请查看 The way they built the zeit.co/vercel dashboard (fully static)

上的 post

here, using next-redux-wrappergetStaticProps 访问状态。

如果您放置了 cookie 并想阅读它们,您可以在 getServerSideProps ctx.req.cookies 此处获取它们,您的 cookie

这里是 link 所以你不应该尝试在 getStaticProps 中获取 cookie https://github.com/vercel/next.js/discussions/11734#discussioncomment-3993