Skip to content

Commit

Permalink
Don't overwrite custom etag (#3348)
Browse files Browse the repository at this point in the history
* Don't overwrite custom etag

* Fix code style

* Add test and changeset for custom etag

* Update .changeset/clever-readers-turn.md

* only generate etags for responses that dont have them already

Co-authored-by: Rich Harris <[email protected]>
  • Loading branch information
cristovao-trevisan and Rich-Harris authored Jan 15, 2022
1 parent 55bfa3d commit 668b0aa
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/clever-readers-turn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Preserve explicit ETag header
5 changes: 3 additions & 2 deletions packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,9 @@ export async function respond(incoming, options, state = {}) {
: await render_page(request, route, match, options, state, ssr);

if (response) {
// inject ETags for 200 responses
if (response.status === 200) {
// inject ETags for 200 responses, if the endpoint
// doesn't have its own ETag handling
if (response.status === 200 && !response.headers.etag) {
const cache_control = get_single_valued_header(response.headers, 'cache-control');
if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
let if_none_match_value = request.headers['if-none-match'];
Expand Down
10 changes: 10 additions & 0 deletions packages/kit/test/apps/basics/src/routes/etag/custom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/** @type {import('@sveltejs/kit').RequestHandler} */
export function get({ headers }) {
if (headers['if-none-match'] === '@1234@') return { status: 304 };
return {
body: `${Math.random()}`,
headers: {
etag: '@1234@'
}
};
}
14 changes: 14 additions & 0 deletions packages/kit/test/apps/basics/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,20 @@ test.describe.parallel('ETags', () => {

expect(r2.status()).toBe(304);
});

test('custom etag', async ({ request }) => {
const r1 = await request.get('/etag/custom');
const etag = r1.headers()['etag'];
expect(etag).toBe('@1234@');

const r2 = await request.get('/etag/custom', {
headers: {
'if-none-match': '@1234@'
}
});

expect(r2.status()).toBe(304);
});
});

test.describe.parallel('Headers', () => {
Expand Down

0 comments on commit 668b0aa

Please sign in to comment.