Commit 79177b7b authored by Tim's avatar Tim Committed by Janka Uryga

fix: unstable_cache should not cache new result in draft mode (#67772)

### What?
In draft mode, as of right now, `unstable_cache` does not read from the
static store, but still write to it. This leads to the following
scenario:

1. Content Editor enters draft mode to test his content
2. Content Editor skips cache and reads preview data
3. Preview data is written to store
4. Random user without draft mode receives preview data until cache is
revalidated again

### Why?
There's an early exit before reading from the cache - the new result is
written to the cache nonetheless though.

### How?
New result is only cached if draft mode is disabled.
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent df864ec8
...@@ -259,15 +259,19 @@ export function unstable_cache<T extends Callback>( ...@@ -259,15 +259,19 @@ export function unstable_cache<T extends Callback>(
cb, cb,
...args ...args
) )
cacheNewResult(
result, if (!store.isDraftMode) {
incrementalCache, cacheNewResult(
cacheKey, result,
tags, incrementalCache,
options.revalidate, cacheKey,
fetchIdx, tags,
fetchUrl options.revalidate,
) fetchIdx,
fetchUrl
)
}
return result return result
} else { } else {
noStoreFetchIdx += 1 noStoreFetchIdx += 1
......
...@@ -3253,6 +3253,26 @@ describe('app-dir static/dynamic handling', () => { ...@@ -3253,6 +3253,26 @@ describe('app-dir static/dynamic handling', () => {
expect(data).not.toEqual(data2) expect(data).not.toEqual(data2)
}) })
it('should not cache new result in draft mode', async () => {
const draftRes = await next.fetch('/api/draft-mode?status=enable')
const setCookie = draftRes.headers.get('set-cookie')
const cookieHeader = { Cookie: setCookie?.split(';', 1)[0] }
expect(cookieHeader.Cookie).toBeTruthy()
const res = await next.fetch('/unstable-cache/dynamic', {
headers: cookieHeader,
})
const html = await res.text()
const data = cheerio.load(html)('#cached-data').text()
const res2 = await next.fetch('/unstable-cache/dynamic')
const html2 = await res2.text()
const data2 = cheerio.load(html2)('#cached-data').text()
expect(data).not.toEqual(data2)
})
it('should not error when retrieving the value undefined', async () => { it('should not error when retrieving the value undefined', async () => {
const res = await next.fetch('/unstable-cache/dynamic-undefined') const res = await next.fetch('/unstable-cache/dynamic-undefined')
const html = await res.text() const html = await res.text()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment