Unverified Commit 74153e12 authored by Giovanni Fumagalli's avatar Giovanni Fumagalli Committed by GitHub

Prevent caching page with 304 status (#57737)

I think that sometimes when a revalidation happens from a request with
caching headers this causing the 304 status to be cached.

This PR ensures the 304 from an initial response doesn't affect a
background revalidation.

Fixes: https://github.com/vercel/next.js/issues/56580

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent ac54377e
......@@ -1491,6 +1491,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return
}
const { req, res } = ctx
const originalStatus = res.statusCode
const { body, type } = payload
let { revalidate } = payload
if (!res.sent) {
......@@ -1502,13 +1503,14 @@ export default abstract class Server<ServerOptions extends Options = Options> {
revalidate = undefined
}
return this.sendRenderResult(req, res, {
await this.sendRenderResult(req, res, {
result: body,
type,
generateEtags,
poweredByHeader,
revalidate,
})
res.statusCode = originalStatus
}
}
......
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default async function Page() {
const time = await new Promise((resolve) => {
setTimeout(500, resolve(new Date().getTime()))
})
return <div>Time: {time}</div>
}
export const revalidate = 1
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { join } from 'path'
import { fetchViaHTTP, waitFor } from 'next-test-utils'
describe('app-dir-prevent-304-caching', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'next.config.js': new FileRef(join(__dirname, 'next.config.js')),
app: new FileRef(join(__dirname, 'app')),
},
})
})
afterAll(() => next.destroy())
// https://github.com/vercel/next.js/issues/56580
it('should not cache 304 status', async () => {
// Fresh call
const rFresh = await fetchViaHTTP(next.url, '/')
expect(rFresh.status).toBe(200)
await waitFor(500)
// Cache HIT but still 200
const rHit = await fetchViaHTTP(
next.url,
'/',
{},
{
headers: {
'If-None-Match': rFresh.headers.get('etag'),
},
}
)
expect(rHit.status).toBe(200)
await waitFor(500)
// Here happens the race condition
const r304 = await fetchViaHTTP(
next.url,
'/',
{},
{
headers: {
'If-None-Match': rHit.headers.get('etag'),
},
}
)
expect(r304.status).toBe(304)
// ... Postponed but should not save 304 ...
await waitFor(1000)
// Now without cache headers should 200
const rStillFresh = await fetchViaHTTP(next.url, '/')
expect(rStillFresh.status).toBe(200)
})
})
/** @type {import("next").NextConfig} */
const nextConfig = {}
module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment