Skip to content

Commit

Permalink
Fix an issue where cache fails to match on Oxygen/Cloudflare (#2530)
Browse files Browse the repository at this point in the history
The URL requires to be URI encoded to properly match
  • Loading branch information
blittle committed Jul 19, 2023
1 parent ca65e24 commit 1e6953d
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/smooth-dryers-march.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/hydrogen': patch
---

Fix an issue where cache doesn't properly match requests
19 changes: 8 additions & 11 deletions packages/hydrogen/src/foundation/Cache/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,22 +102,19 @@ export async function setItemInCache(
const cacheControl = getCacheControlSetting(userCacheOptions);

// The padded cache-control to mimic stale-while-revalidate
request.headers.set(
'cache-control',
generateDefaultCacheControlHeader(
getCacheControlSetting(cacheControl, {
maxAge:
(cacheControl.maxAge || 0) + (cacheControl.staleWhileRevalidate || 0),
})
)
const paddedCacheControlString = generateDefaultCacheControlHeader(
getCacheControlSetting(cacheControl, {
maxAge:
(cacheControl.maxAge || 0) + (cacheControl.staleWhileRevalidate || 0),
})
);

// The cache-control we want to set on response
const cacheControlString = generateDefaultCacheControlHeader(
getCacheControlSetting(cacheControl)
);
const cacheControlString = generateDefaultCacheControlHeader(cacheControl);

// CF will override cache-control, so we need to keep a
// non-modified real-cache-control
response.headers.set('cache-control', paddedCacheControlString);
response.headers.set('real-cache-control', cacheControlString);
response.headers.set('cache-put-date', new Date().toUTCString());

Expand Down
2 changes: 1 addition & 1 deletion packages/hydrogen/src/utilities/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ export function hashKey(queryKey: QueryKey): string {
}
}

return hash;
return encodeURIComponent(hash);
}
8 changes: 6 additions & 2 deletions packages/hydrogen/src/utilities/tests/hash.vitest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ describe('Hash key for subrequests', () => {
});

it('supports arrays of strings and objects', () => {
expect(hashKey(['hello', {world: true}])).toEqual('hello{"world":true}');
expect(hashKey(['hello', {world: true}])).toEqual(
'hello%7B%22world%22%3Atrue%7D'
);
});

it('supports useShopQuery-like keys', () => {
Expand Down Expand Up @@ -43,6 +45,8 @@ describe('Hash key for subrequests', () => {
NaN,
['subarray'],
])
).toEqual('hello() => "world"11Infinity{}NaN["subarray"]');
).toEqual(
'hello()%20%3D%3E%20%22world%2211Infinity%7B%7DNaN%5B%22subarray%22%5D'
);
});
});

0 comments on commit 1e6953d

Please sign in to comment.