Next.js 能否为 SSR 页面返回 304 Not Modified 状态?

Alm*_*bay 4 reactjs server-side-rendering next.js

很明显,Next.js 对 SSG 页面返回 304 Not Modified HTTP 状态,但它可以对实时渲染的页面执行此操作吗?

反过来说,当最初请求 SSR 页面时,Next.js 是否返回 ETag 标头?

谢谢。

Már*_*son 5

从 Next.js v13 开始(至少)似乎可以,但您必须设置状态代码和ETag/Last-Modified并自己检查传入的If-None-Match/If-Modified-Since标头。

模拟代码:

export const getServerSideProps = async (ctx) => {}
  const { req, res } = ctx;

  if (shouldReturnNotModified(req)) {
    res.statusCode = 304;
    return { props: {} };
  }
  
  res.setHeader('ETag', generateETag(req));
  return { 
    props: await fetchAllTheProps(req),
  };
}

// This is not rendered if the `res.statusCode` is 304
export default function MyPage (props) {
  return (
    <div>
      Render the page's 200 OK response 
      using all the props
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

Next.js 唯一真正有帮助的是,如果它注意到您已设置res.statusCode为 304,则跳过渲染响应正文。

这些都没有正式记录。(在 Nextjs 文档中搜索“304”会返回 0 个结果。)