Skip to content
Open
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
22 changes: 22 additions & 0 deletions packages/edge-config/src/utils/fetch-with-cached-response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,28 @@ describe('fetchWithCachedResponse', () => {
await expect(data2.json()).resolves.toEqual({ name: 'John' });
});

it('should NOT serve stale content after stale-if-error window expires', async () => {
fetchMock.mockResponseOnce(JSON.stringify({ name: 'John' }), {
headers: { ETag: 'abc123', 'content-type': 'application/json' },
});

// First request — populate cache
await fetchWithCachedResponse('https://example.com/api/data');

// Advance past the 10s stale-if-error window (11 seconds)
jest.advanceTimersByTime(11000);

// Second request: network error, but stale-if-error=10 has expired
fetchMock.mockAbortOnce();

// Should throw because stale-if-error window has expired
await expect(
fetchWithCachedResponse('https://example.com/api/data', {
headers: new Headers({ 'Cache-Control': 'stale-if-error=10' }),
}),
).rejects.toThrow();
});

it('should respect stale-if-error on network faults', async () => {
fetchMock.mockResponseOnce(JSON.stringify({ name: 'John' }), {
headers: { ETag: 'abc123', 'content-type': 'application/json' },
Expand Down
4 changes: 2 additions & 2 deletions packages/edge-config/src/utils/fetch-with-cached-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ function createHandleStaleIfError(
case 503:
case 504:
return typeof staleIfError === 'number' &&
cachedResponseEntry.time < Date.now() + staleIfError * 1000
Date.now() < cachedResponseEntry.time + staleIfError * 1000
? createResponse(cachedResponseEntry)
: response;
default:
Expand All @@ -69,7 +69,7 @@ function createHandleStaleIfErrorException(
): ResponseWithCachedResponse {
if (
typeof staleIfError === 'number' &&
cachedResponseEntry.time < Date.now() + staleIfError * 1000
Date.now() < cachedResponseEntry.time + staleIfError * 1000
) {
return createResponse(cachedResponseEntry);
}
Expand Down