Unverified Commit bfd10b36 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Add cache reason for using fetch with noStore (#60630)

When you're using `noStore()` with `fetch` it's currently saying "auto
cache" in cache missed reason, adding "noStore call" here to show it's
caused by using with `unstable_noStore`

```
 GET /no-store 200 in 4069ms
  │ GET https://next-data-api-endpoint.vercel.app/api/random?another-no-cache 200 in 257ms (cache: SKIP)
  │  │  Cache missed reason: (noStore call)
```

Closes NEXT-2097
parent 126c7f24
...@@ -51,6 +51,7 @@ export interface StaticGenerationStore { ...@@ -51,6 +51,7 @@ export interface StaticGenerationStore {
fetchMetrics?: FetchMetrics fetchMetrics?: FetchMetrics
isDraftMode?: boolean isDraftMode?: boolean
isUnstableNoStore?: boolean
} }
export type StaticGenerationAsyncStorage = export type StaticGenerationAsyncStorage =
......
...@@ -287,6 +287,7 @@ export function patchFetch({ ...@@ -287,6 +287,7 @@ export function patchFetch({
staticGenerationStore.fetchCache === 'only-no-store' staticGenerationStore.fetchCache === 'only-no-store'
const isForceNoStore = const isForceNoStore =
staticGenerationStore.fetchCache === 'force-no-store' staticGenerationStore.fetchCache === 'force-no-store'
const isUsingNoStore = !!staticGenerationStore.isUnstableNoStore
let _cache = getRequestMeta('cache') let _cache = getRequestMeta('cache')
let cacheReason = '' let cacheReason = ''
...@@ -386,6 +387,9 @@ export function patchFetch({ ...@@ -386,6 +387,9 @@ export function patchFetch({
} else if (isDefaultNoStore) { } else if (isDefaultNoStore) {
revalidate = 0 revalidate = 0
cacheReason = 'fetchCache = default-no-store' cacheReason = 'fetchCache = default-no-store'
} else if (isUsingNoStore) {
revalidate = 0
cacheReason = 'noStore call'
} else { } else {
cacheReason = 'auto cache' cacheReason = 'auto cache'
revalidate = revalidate =
......
...@@ -10,6 +10,10 @@ export function unstable_noStore() { ...@@ -10,6 +10,10 @@ export function unstable_noStore() {
return return
} }
// Mark the static generation context has unstable_noStore
if (staticGenerationStore) {
staticGenerationStore.isUnstableNoStore = true
}
staticGenerationBailout('unstable_noStore', { staticGenerationBailout('unstable_noStore', {
link: 'https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering', link: 'https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering',
}) })
......
import { unstable_noStore } from 'next/cache'
async function getUncachedRandomData() {
unstable_noStore()
const res = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?another-no-cache'
)
const data = await res.json()
return data
}
export default async function Page() {
const uncachedData = await getUncachedRandomData()
console.log('uncachedData', uncachedData)
return (
<div>
<p>random: {Math.random()}</p>
<p id="uncached-data">uncachedData: {uncachedData}</p>
</div>
)
}
import path from 'path' import path from 'path'
import fs from 'fs' import fs from 'fs'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import { check } from 'next-test-utils' import { retry } from 'next-test-utils'
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
function parseLogsFromCli(cliOutput: string) { function parseLogsFromCli(cliOutput: string) {
...@@ -56,18 +56,12 @@ createNextDescribe( ...@@ -56,18 +56,12 @@ createNextDescribe(
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
await next.fetch('/default-cache') await next.fetch('/default-cache')
await check(() => { await retry(() => {
const logs = stripAnsi(next.cliOutput.slice(outputIndex)) const logs = stripAnsi(next.cliOutput.slice(outputIndex))
const hasLogs = logs.includes('GET /default-cache 200') const hasLogs = logs.includes('GET /default-cache 200')
if (isNextDev && hasLogs) { expect(isNextDev ? hasLogs : !hasLogs).toBe(true)
return 'success' })
}
if (!isNextDev && !hasLogs) {
return 'success'
}
}, 'success')
}) })
if (isNextDev) { if (isNextDev) {
...@@ -75,7 +69,7 @@ createNextDescribe( ...@@ -75,7 +69,7 @@ createNextDescribe(
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
await next.fetch('/default-cache') await next.fetch('/default-cache')
await check(() => { await retry(() => {
const logs = parseLogsFromCli(next.cliOutput.slice(outputIndex)) const logs = parseLogsFromCli(next.cliOutput.slice(outputIndex))
const logEntry = logs.find((log) => const logEntry = logs.find((log) =>
...@@ -86,26 +80,22 @@ createNextDescribe( ...@@ -86,26 +80,22 @@ createNextDescribe(
!withFullUrlFetches !withFullUrlFetches
) )
if (logEntry?.cache === 'cache: no-cache') { expect(logEntry?.cache).toBe('cache: no-cache')
return 'success' })
}
}, 'success')
}) })
it("should log 'skip' cache status with a reason when revalidate: 0 is used", async () => { it("should log 'skip' cache status with a reason when revalidate: 0 is used", async () => {
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
await next.fetch('/default-cache') await next.fetch('/default-cache')
await check(() => { await retry(() => {
const logs = parseLogsFromCli(next.cliOutput.slice(outputIndex)) const logs = parseLogsFromCli(next.cliOutput.slice(outputIndex))
const logEntry = logs.find((log) => const logEntry = logs.find((log) =>
log.url.includes('api/random?revalidate-0') log.url.includes('api/random?revalidate-0')
) )
if (logEntry?.cache === 'revalidate: 0') { expect(logEntry?.cache).toBe('revalidate: 0')
return 'success' })
}
}, 'success')
}) })
it("should log 'skip' cache status with a reason when the browser indicates caching should be ignored", async () => { it("should log 'skip' cache status with a reason when the browser indicates caching should be ignored", async () => {
...@@ -113,26 +103,24 @@ createNextDescribe( ...@@ -113,26 +103,24 @@ createNextDescribe(
await next.fetch('/default-cache', { await next.fetch('/default-cache', {
headers: { 'Cache-Control': 'no-cache' }, headers: { 'Cache-Control': 'no-cache' },
}) })
await check(() => { await retry(() => {
const logs = parseLogsFromCli(next.cliOutput.slice(outputIndex)) const logs = parseLogsFromCli(next.cliOutput.slice(outputIndex))
const logEntry = logs.find((log) => const logEntry = logs.find((log) =>
log.url.includes('api/random?auto-cache') log.url.includes('api/random?auto-cache')
) )
if ( expect(logEntry?.cache).toBe(
logEntry?.cache === 'cache-control: no-cache (hard refresh)' 'cache-control: no-cache (hard refresh)'
) { )
return 'success' })
}
}, 'success')
}) })
it('should log requests with correct indentation', async () => { it('should log requests with correct indentation', async () => {
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
await next.fetch('/default-cache') await next.fetch('/default-cache')
await check(() => { await retry(() => {
const logs = stripAnsi(next.cliOutput.slice(outputIndex)) const logs = stripAnsi(next.cliOutput.slice(outputIndex))
const hasLogs = const hasLogs =
logs.includes(' GET /default-cache') && logs.includes(' GET /default-cache') &&
...@@ -140,25 +128,30 @@ createNextDescribe( ...@@ -140,25 +128,30 @@ createNextDescribe(
logs.includes(' │ │ GET ') && logs.includes(' │ │ GET ') &&
logs.includes(' │ │ Cache missed reason') logs.includes(' │ │ Cache missed reason')
if (hasLogs) { expect(hasLogs).toBe(true)
return 'success' })
} })
}, 'success')
it('should show cache reason of noStore when use with fetch', async () => {
const logLength = next.cliOutput.length
await next.fetch('/no-store')
await retry(() => {
const output = stripAnsi(next.cliOutput.slice(logLength))
expect(output).toContain('Cache missed reason: (noStore call)')
})
}) })
} }
} else { } else {
// No fetches logging enabled
it('should not log fetch requests at all', async () => { it('should not log fetch requests at all', async () => {
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
await next.fetch('/default-cache') await next.fetch('/default-cache')
await check(() => { await retry(() => {
const logs = stripAnsi(next.cliOutput.slice(outputIndex)) const logs = stripAnsi(next.cliOutput.slice(outputIndex))
if (logs.includes('GET /default-cache 200')) { expect(logs).not.toContain('GET /default-cache 200')
return 'fail' })
}
return 'success'
}, 'success')
}) })
} }
...@@ -167,28 +160,24 @@ createNextDescribe( ...@@ -167,28 +160,24 @@ createNextDescribe(
const logLength = next.cliOutput.length const logLength = next.cliOutput.length
await next.fetch('/') await next.fetch('/')
await check(() => { await retry(() => {
const output = stripAnsi(next.cliOutput.slice(logLength)) const output = stripAnsi(next.cliOutput.slice(logLength))
expect(output).toContain('/') expect(output).toContain('/')
expect(output).not.toContain('/page') expect(output).not.toContain('/page')
})
return 'success'
}, /success/)
}) })
it('should not contain metadata internal segments for dynamic metadata routes', async () => { it('should not contain metadata internal segments for dynamic metadata routes', async () => {
const logLength = next.cliOutput.length const logLength = next.cliOutput.length
await next.fetch('/dynamic/big/icon') await next.fetch('/dynamic/big/icon')
await check(() => { await retry(() => {
const output = stripAnsi(next.cliOutput.slice(logLength)) const output = stripAnsi(next.cliOutput.slice(logLength))
expect(output).toContain('/dynamic/[slug]/icon') expect(output).toContain('/dynamic/[slug]/icon')
expect(output).not.toContain('/(group)') expect(output).not.toContain('/(group)')
expect(output).not.toContain('[[...__metadata_id__]]') expect(output).not.toContain('[[...__metadata_id__]]')
expect(output).not.toContain('/route') expect(output).not.toContain('/route')
})
return 'success'
}, /success/)
}) })
} }
} }
......
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