Unverified Commit 451a54cb authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

cache: add unstable_noStore API (#56930)

This PR introduces a new API, `unstable_noStore`, which will allow users to declaratively opt out of caching anywhere during static generation in the same way that you can specify `cache: 'no-store'` on a fetch call in Next.js.

An important caveat and difference from just calling `cookies()` to opt-out of static generation is that this won't opt you out when called from within `unstable_cache` and instead defers to the cache configuration to it.

```
import {unstable_noStore as noStore} from 'next/cache';

export default async function Component() {
  noStore();
  const result = await db.query(...);
}
```
parent 218d0709
export { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cache'
export { revalidatePath } from 'next/dist/server/web/spec-extension/revalidate-path'
export { revalidateTag } from 'next/dist/server/web/spec-extension/revalidate-tag'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
......@@ -5,6 +5,9 @@ const cacheExports = {
.revalidateTag,
revalidatePath: require('next/dist/server/web/spec-extension/revalidate-path')
.revalidatePath,
unstable_noStore:
require('next/dist/server/web/spec-extension/unstable-no-store')
.unstable_noStore,
}
// https://nodejs.org/api/esm.html#commonjs-namespaces
......@@ -15,3 +18,4 @@ module.exports = cacheExports
exports.unstable_cache = cacheExports.unstable_cache
exports.revalidatePath = cacheExports.revalidatePath
exports.revalidateTag = cacheExports.revalidateTag
exports.unstable_noStore = cacheExports.unstable_noStore
......@@ -12,6 +12,7 @@ export interface StaticGenerationStore {
readonly isOnDemandRevalidate?: boolean
readonly isPrerendering?: boolean
readonly isRevalidate?: boolean
readonly isUnstableCacheCallback?: boolean
forceDynamic?: boolean
fetchCache?:
......
// This file is for modularized imports for next/server to get fully-treeshaking.
export { unstable_noStore as default } from '../spec-extension/unstable-no-store'
......@@ -54,6 +54,7 @@ export function unstable_cache<T extends Callback>(
fetchCache: 'only-no-store',
urlPathname: store?.urlPathname || '/',
isStaticGeneration: !!store?.isStaticGeneration,
isUnstableCacheCallback: true,
},
async () => {
const tags = validateTags(
......
import { staticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage.external'
import { staticGenerationBailout } from '../../../client/components/static-generation-bailout'
export function unstable_noStore() {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
if (staticGenerationStore?.isUnstableCacheCallback) {
// if called within a next/cache call, we want to cache the result
// and defer to the next/cache call to handle how to cache the result.
return
}
staticGenerationBailout('unstable_noStore', {
link: 'https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering',
})
}
......@@ -710,6 +710,12 @@ createNextDescribe(
'articles/[slug]/page_client-reference-manifest.js',
'articles/works.html',
'articles/works.rsc',
'no-store/dynamic/page.js',
'no-store/dynamic/page_client-reference-manifest.js',
'no-store/static.html',
'no-store/static.rsc',
'no-store/static/page.js',
'no-store/static/page_client-reference-manifest.js',
].sort()
)
})
......@@ -1018,6 +1024,22 @@ createNextDescribe(
"initialRevalidateSeconds": false,
"srcRoute": "/hooks/use-search-params/with-suspense",
},
"/no-store/static": Object {
"dataRoute": "/no-store/static.rsc",
"experimentalBypassFor": Array [
Object {
"key": "Next-Action",
"type": "header",
},
Object {
"key": "content-type",
"type": "header",
"value": "multipart/form-data",
},
],
"initialRevalidateSeconds": false,
"srcRoute": "/no-store/static",
},
"/partial-gen-params-no-additional-lang/en/RAND": Object {
"dataRoute": "/partial-gen-params-no-additional-lang/en/RAND.rsc",
"experimentalBypassFor": Array [
......@@ -2921,6 +2943,30 @@ createNextDescribe(
})
})
describe('unstable_noStore', () => {
it('should opt-out of static optimization', async () => {
const res = await next.fetch('/no-store/dynamic')
const html = await res.text()
const data = cheerio.load(html)('#uncached-data').text()
const res2 = await next.fetch('/no-store/dynamic')
const html2 = await res2.text()
const data2 = cheerio.load(html2)('#uncached-data').text()
expect(data).not.toEqual(data2)
})
it('should not opt-out of static optimization when used in next/cache', async () => {
const res = await next.fetch('/no-store/static')
const html = await res.text()
const data = cheerio.load(html)('#data').text()
const res2 = await next.fetch('/no-store/static')
const html2 = await res2.text()
const data2 = cheerio.load(html2)('#data').text()
expect(data).toEqual(data2)
})
})
it('should keep querystring on static page', async () => {
const browser = await next.browser('/blog/tim?message=hello-world')
const checkUrl = async () =>
......
import { getUncachedRandomData } from '../no-store-fn'
export default async function Page() {
const uncachedData = await getUncachedRandomData()
return (
<div>
<p>random: {Math.random()}</p>
<p id="uncached-data">uncachedData: {uncachedData.random}</p>
</div>
)
}
import { unstable_noStore } from 'next/cache'
export function getUncachedRandomData() {
unstable_noStore()
return {
random: Math.random(),
}
}
'use client'
export function RevalidateButton({ onClick }) {
return (
<form action={onClick}>
<button type="submit">revalidate</button>
</form>
)
}
import { revalidateTag, unstable_cache } from 'next/cache'
import { getUncachedRandomData } from '../no-store-fn'
import { RevalidateButton } from '../revalidate-button'
export default async function Page() {
async function revalidate() {
'use server'
await revalidateTag('no-store-fn')
}
const cachedData = await unstable_cache(
async () => {
return getUncachedRandomData()
},
['random'],
{
tags: ['no-store-fn'],
}
)()
return (
<div>
<p>random: {Math.random()}</p>
<p id="data">cachedData: {cachedData.random}</p>
<RevalidateButton onClick={revalidate} />
</div>
)
}
......@@ -4,6 +4,7 @@ module.exports = {
logging: {
level: 'verbose',
},
serverActions: true,
incrementalCacheHandlerPath: process.env.CUSTOM_CACHE_HANDLER,
},
......
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