如何仅在 Next.JS 中禁用特定页面上的缓存

Dr.*_*ulo 7 reactjs next.js

我正在运行一个作业聚合器,我希望避免缓存我的帖子提要,因为它向我的用户显示过时的结果。我们在 Next.JS 上运行。

我已经搜索了他们的文档,但没有找到如何去做的方法......

有人有想法吗?

我假设它在 next.config.js 上,但我不知道具体如何。

Ale*_*ggi 12

通过 next.config.js

将标题设置no-cache在您想要的路径上。

module.exports = {
  headers: () => [
    {
      source: '/:path*',
      headers: [
        {
          key: 'Cache-Control',
          value: 'no-store',
        },
      ],
    },
  ],
}
Run Code Online (Sandbox Code Playgroud)

文档:NextJS 标头覆盖行为


Vin*_*nie 3

如果服务器端渲染这似乎可行

Page.getInitialProps = async ({ store, res }) => {
    if (res) {
        // res available only at server
        // no-store disable bfCache for any browser. So your HTML will not be cached
        res.setHeader('Cache-Control', 'no-store');
    }

    await store.dispatch(action());
    return {};
};
Run Code Online (Sandbox Code Playgroud)