From b17ca02695cfa93b29871cb8fb30ebb2200123a8 Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Wed, 22 May 2024 13:54:16 -0500 Subject: [PATCH] Skip setting to fetch cache when not modified (#66055) To avoid extra network hops we can compare existing cache entries we've already fetched and see if the revalidated value matches and if it does we can avoid sending the set request with the identical data. --- .../lib/incremental-cache/fetch-cache.ts | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/next/src/server/lib/incremental-cache/fetch-cache.ts b/packages/next/src/server/lib/incremental-cache/fetch-cache.ts index 6ecb7048eda90..be34cf90394ee 100644 --- a/packages/next/src/server/lib/incremental-cache/fetch-cache.ts +++ b/packages/next/src/server/lib/incremental-cache/fetch-cache.ts @@ -297,6 +297,26 @@ export default class FetchCache implements CacheHandler { public async set(...args: Parameters) { const [key, data, ctx] = args + + const newValue = data?.kind === 'FETCH' ? data.data : undefined + const existingCache = memoryCache?.get(key) + const existingValue = existingCache?.value + if ( + existingValue?.kind === 'FETCH' && + Object.keys(existingValue.data).every( + (field) => + JSON.stringify( + (existingValue.data as Record)[field] + ) === + JSON.stringify((newValue as Record)[field]) + ) + ) { + if (this.debug) { + console.log(`skipping cache set for ${key} as not modified`) + } + return + } + const { fetchCache, fetchIdx, fetchUrl, tags } = ctx if (!fetchCache) return