diff --git a/packages/http-cache/__tests__/renderRouteCallback.spec.ts b/packages/http-cache/__tests__/renderRouteCallback.spec.ts index 9497cc8801..ac23e9a372 100644 --- a/packages/http-cache/__tests__/renderRouteCallback.spec.ts +++ b/packages/http-cache/__tests__/renderRouteCallback.spec.ts @@ -6,7 +6,8 @@ import renderRouteCallback from '../nuxt/renderRouteCallback'; const response = { res: { setHeader: jest.fn(), - removeHeader: jest.fn() + removeHeader: jest.fn(), + headersSent: false } }; @@ -16,6 +17,9 @@ const response = { jest.mock('../nuxt/isUrlMatchingRule', () => jest.fn(() => true)); describe('renderRouteCallback', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); it('adds default cache-control header', () => { const options = {}; @@ -60,4 +64,10 @@ describe('renderRouteCallback', () => { renderRouteCallback(options)('/c/123', null, response); expect(response.res.removeHeader).toBeCalledWith('Cache-Control'); }); + + it('does not set headers if they had been sent already', () => { + const options = {}; + renderRouteCallback(options)('/c/123', null, { res: { ...response.res, headersSent: true }}); + expect(response.res.setHeader).toHaveBeenCalledTimes(0); + }); }); diff --git a/packages/http-cache/nuxt/renderRouteCallback.ts b/packages/http-cache/nuxt/renderRouteCallback.ts index e36597bba8..83217ed186 100644 --- a/packages/http-cache/nuxt/renderRouteCallback.ts +++ b/packages/http-cache/nuxt/renderRouteCallback.ts @@ -2,6 +2,7 @@ import isUrlMatchingRule from './isUrlMatchingRule'; import { HttpCacheModuleParams } from './types'; const renderRouteCallback = ({ default: defaultHeaderValue = 'max-age=60', matchRoute = {} }: HttpCacheModuleParams) => (url, result, { res }): void => { + if (res.headersSent) return; res.setHeader('Cache-Control', defaultHeaderValue); Object.entries(matchRoute).map(([rule, headerValue]: [string, string]): void => {