From 1f389978343dc472b31ee3865e4068702eab0f21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eduardo=20Bou=C3=A7as?= Date: Wed, 15 Oct 2025 08:50:53 +0100 Subject: [PATCH] fix: make `fetchWithCache` stop throwing on uncacheable response --- packages/cache/src/fetchwithcache.test.ts | 22 ++++++++++++++++++++++ packages/cache/src/fetchwithcache.ts | 5 ++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/packages/cache/src/fetchwithcache.test.ts b/packages/cache/src/fetchwithcache.test.ts index 555c712c..a1a786d5 100644 --- a/packages/cache/src/fetchwithcache.test.ts +++ b/packages/cache/src/fetchwithcache.test.ts @@ -307,4 +307,26 @@ describe('`fetchWithCache`', () => { mockFetch.restore() expect(mockFetch.fulfilled).toBe(true) }) + + test('Does not throw an error when response returns a 5xx error', async () => { + const mockFetch = new MockFetch() + .get({ + url: 'https://example.netlify/.netlify/cache/https%3A%2F%2Fnetlify.com%2F', + response: new Response(null, { status: 404 }), + }) + .get({ + url: 'https://netlify.com/', + response: new Response('Internal Server Error', { status: 500 }), + }) + .inject() + const resourceURL = 'https://netlify.com' + + const response = await fetchWithCache(resourceURL) + + expect(response.status).toBe(500) + expect(await response.text()).toBe('Internal Server Error') + + mockFetch.restore() + expect(mockFetch.fulfilled).toBe(true) + }) }) diff --git a/packages/cache/src/fetchwithcache.ts b/packages/cache/src/fetchwithcache.ts index 77f7b3f4..9b613aee 100644 --- a/packages/cache/src/fetchwithcache.ts +++ b/packages/cache/src/fetchwithcache.ts @@ -129,7 +129,10 @@ export const fetchWithCache: FetchWithCache = async ( const cacheResponse = new Response(cacheStream, fresh) applyHeaders(cacheResponse.headers, cacheHeaders(cacheSettings)) - const cachePut = cache.put(request, cacheResponse) + const cachePut = cache.put(request, cacheResponse).catch(() => { + // If we fail to cache the response, we want to swallow the error because + // we'll still return the result of `fetch`. + }) if (onCachePut) { await onCachePut(cachePut)