Skip to content

Commit bd57e25

Browse files
authored
don't send response headers if response is done (#26550)
* don't send response headers if response is done * better
1 parent 2b873fd commit bd57e25

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

middleware/handle-errors.js

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,27 +37,31 @@ export default async function handleError(error, req, res, next) {
3737
// Note, not using console.error() because it's arguably handled.
3838
// Some tests might actually expect a 500 error.
3939

40+
const responseDone = res.headersSent || req.aborted
41+
4042
if (req.path.startsWith('/assets') || req.path.startsWith('/_next/static')) {
41-
// By default, Fastly will cache 404 responses unless otherwise
42-
// told not to.
43-
// See https://docs.fastly.com/en/guides/how-caching-and-cdns-work#http-status-codes-cached-by-default
44-
// Let's cache our 404'ing assets conservatively.
45-
// The Cache-Control is short, and let's use the default surrogate
46-
// key just in case it was a mistake.
47-
cacheControl(res)
48-
// Undo the cookie setting that CSRF sets.
49-
res.removeHeader('set-cookie')
50-
// Makes sure the surrogate key is NOT the manual one if it failed.
51-
// This basically unsets what was assumed in the beginning of
52-
// loading all the middlewares.
53-
setFastlySurrogateKey(res, SURROGATE_ENUMS.DEFAULT)
43+
if (!responseDone) {
44+
// By default, Fastly will cache 404 responses unless otherwise
45+
// told not to.
46+
// See https://docs.fastly.com/en/guides/how-caching-and-cdns-work#http-status-codes-cached-by-default
47+
// Let's cache our 404'ing assets conservatively.
48+
// The Cache-Control is short, and let's use the default surrogate
49+
// key just in case it was a mistake.
50+
cacheControl(res)
51+
// Undo the cookie setting that CSRF sets.
52+
res.removeHeader('set-cookie')
53+
// Makes sure the surrogate key is NOT the manual one if it failed.
54+
// This basically unsets what was assumed in the beginning of
55+
// loading all the middlewares.
56+
setFastlySurrogateKey(res, SURROGATE_ENUMS.DEFAULT)
57+
}
5458
} else if (process.env.NODE_ENV === 'test') {
5559
console.warn('An error occurrred in some middleware handler', error)
5660
}
5761

5862
try {
5963
// If the headers have already been sent or the request was aborted...
60-
if (res.headersSent || req.aborted) {
64+
if (responseDone) {
6165
// Report to Failbot
6266
await logException(error, req)
6367

0 commit comments

Comments
 (0)