From e535e5228035f6efc35e137c68dcfbd0979b738e Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Wed, 9 Feb 2022 15:03:15 -0500 Subject: [PATCH] minimize caching on static asset 404s (#25192) --- middleware/handle-errors.js | 36 ++++++++++++++++++++++++++++---- tests/rendering/static-assets.js | 9 ++++++-- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/middleware/handle-errors.js b/middleware/handle-errors.js index e6fd42e904..1ecffc2dd6 100644 --- a/middleware/handle-errors.js +++ b/middleware/handle-errors.js @@ -1,5 +1,9 @@ import FailBot from '../lib/failbot.js' import { nextApp } from './next.js' +import { setFastlySurrogateKey, SURROGATE_ENUMS } from './set-fastly-surrogate-key.js' +import { cacheControlFactory } from './cache-control.js' + +const cacheControl = cacheControlFactory(60) // 1 minute function shouldLogException(error) { const IGNORED_ERRORS = [ @@ -32,10 +36,34 @@ export default async function handleError(error, req, res, next) { // anywhere. So this is why we log it additionally. // Note, not using console.error() because it's arguably handled. // Some tests might actually expect a 500 error. - if ( - process.env.NODE_ENV === 'test' && - !(req.path.startsWith('/assets') || req.path.startsWith('/_next/static')) - ) { + + if (req.path.startsWith('/assets') || req.path.startsWith('/_next/static')) { + // By default, Fastly will cache 404 responses unless otherwise + // told not to. + // See https://docs.fastly.com/en/guides/how-caching-and-cdns-work#http-status-codes-cached-by-default + // Most of the time, that's a good thing! Especially, if bombarded + // for some static asset that we don't have. + // E.g. `ab -n 10000 https://docs.github.com/assets/doesnotexist.png` + // But due to potential timing issue related to how the servers start, + // what might happen is that a new insteance comes up that + // contains `