Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): prevent http cache module from setting headers after they had been sent #6720

Merged
merged 2 commits into from
May 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/http-cache/__tests__/renderRouteCallback.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import renderRouteCallback from '../nuxt/renderRouteCallback';
const response = {
res: {
setHeader: jest.fn(),
removeHeader: jest.fn()
removeHeader: jest.fn(),
headersSent: false
}
};

Expand All @@ -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 = {};

Expand Down Expand Up @@ -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);
});
});
1 change: 1 addition & 0 deletions packages/http-cache/nuxt/renderRouteCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down