diff --git a/middleware/fast-head.js b/middleware/fast-head.js new file mode 100644 index 0000000000..b39676a808 --- /dev/null +++ b/middleware/fast-head.js @@ -0,0 +1,16 @@ +import { cacheControlFactory } from './cache-control.js' + +const cacheControl = cacheControlFactory(60 * 60 * 24) + +export default function fastHead(req, res, next) { + const { context } = req + const { page } = context + if (page) { + // Since the *presence* is not affected by the request, we can cache + // this and allow the CDN to hold on to it. + cacheControl(res) + + return res.status(200).send('') + } + next() +} diff --git a/middleware/index.js b/middleware/index.js index 6aa26dc383..16f30a7011 100644 --- a/middleware/index.js +++ b/middleware/index.js @@ -65,6 +65,7 @@ import archivedAssetRedirects from './archived-asset-redirects.js' import favicons from './favicons.js' import setStaticAssetCaching from './static-asset-caching.js' import protect from './overload-protection.js' +import fastHead from './fast-head.js' const { DEPLOYMENT_ENV, NODE_ENV } = process.env const isDevelopment = NODE_ENV === 'development' @@ -309,6 +310,10 @@ export default function (app) { // Check for a dropped connection before proceeding (again) app.use(haltOnDroppedConnection) + // Specifically deal with HEAD requests before doing the slower + // full page rendering. + app.head('/*', fastHead) + // *** Preparation for render-page: contextualizers *** app.use(asyncMiddleware(instrument(releaseNotes, './contextualizers/release-notes'))) app.use(instrument(graphQL, './contextualizers/graphql')) diff --git a/tests/rendering/server.js b/tests/rendering/server.js index 22a5dbc977..aab3c7f5e6 100644 --- a/tests/rendering/server.js +++ b/tests/rendering/server.js @@ -29,8 +29,13 @@ describe('server', () => { test('supports HEAD requests', async () => { const res = await head('/en') expect(res.statusCode).toBe(200) - expect(res.headers).not.toHaveProperty('content-length') + expect(res.headers['content-length']).toBe('0') expect(res.text).toBe('') + // Because the HEAD requests can't be different no matter what's + // in the request headers (Accept-Language or Cookies) + // it's safe to let it cache. The only key is the URL. + expect(res.headers['cache-control']).toContain('public') + expect(res.headers['cache-control']).toMatch(/max-age=\d+/) }) test('renders the homepage', async () => {