Unverified Commit 703830cb authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

allow root params access in private caches (#82125)

Accessing root params in a private cache should work, but I missed it in
the `next/root-params` PR.
```tsx
import { lang } from 'next/root-params'

async function foo() {
  'use cache: private'
  await lang() // this is okay
}
```
With this PR, we'll now allow this (and `unstable_rootParams()`)
parent 2c9fe23c
......@@ -246,6 +246,13 @@ export interface PrivateUseCacheStore extends CommonUseCacheStore {
* access the request cookies.
*/
readonly cookies: ReadonlyRequestCookies
/**
* Private caches don't currently need to track root params in the cache key
* because they're not persisted anywhere, so we can allow root params access
* (unlike public caches)
*/
readonly rootParams: Params
}
export type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore
......
......@@ -41,7 +41,6 @@ export async function unstable_rootParams(): Promise<Params> {
switch (workUnitStore.type) {
case 'cache':
case 'private-cache':
case 'unstable-cache': {
throw new Error(
`Route ${workStore.route} used \`unstable_rootParams()\` inside \`"use cache"\` or \`unstable_cache\`. Support for this API inside cache scopes is planned for a future version of Next.js.`
......@@ -56,6 +55,7 @@ export async function unstable_rootParams(): Promise<Params> {
workStore,
workUnitStore
)
case 'private-cache':
case 'request':
return Promise.resolve(workUnitStore.rootParams)
default:
......@@ -228,7 +228,6 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
switch (workUnitStore.type) {
case 'unstable-cache':
case 'private-cache':
case 'cache': {
throw new Error(
`Route ${workStore.route} used ${apiName} inside \`"use cache"\` or \`unstable_cache\`. Support for this API inside cache scopes is planned for a future version of Next.js.`
......@@ -245,6 +244,7 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
apiName
)
}
case 'private-cache':
case 'request': {
break
}
......
......@@ -187,14 +187,15 @@ function createUseCacheStore(
explicitExpire: undefined,
explicitStale: undefined,
tags: null,
hmrRefreshHash:
outerWorkUnitStore && getHmrRefreshHash(workStore, outerWorkUnitStore),
isHmrRefresh: outerWorkUnitStore?.isHmrRefresh ?? false,
serverComponentsHmrCache: outerWorkUnitStore?.serverComponentsHmrCache,
hmrRefreshHash: getHmrRefreshHash(workStore, outerWorkUnitStore),
isHmrRefresh: outerWorkUnitStore.isHmrRefresh ?? false,
serverComponentsHmrCache: outerWorkUnitStore.serverComponentsHmrCache,
forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore),
draftMode:
outerWorkUnitStore &&
getDraftModeProviderForCacheScope(workStore, outerWorkUnitStore),
draftMode: getDraftModeProviderForCacheScope(
workStore,
outerWorkUnitStore
),
rootParams: outerWorkUnitStore.rootParams,
cookies: outerWorkUnitStore.cookies,
}
} else {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export function generateStaticParams() {
// the param values are not accessed in tests,
// we just need a value here to avoid errors in PPR/cacheComponents
// where we need to provide at least one set of values for root params
return [{ lang: 'foo', locale: 'bar' }]
}
import { lang, locale } from 'next/root-params'
import { connection } from 'next/server'
import { Suspense } from 'react'
export default async function Page() {
return (
<Suspense fallback="Loading...">
<Runtime />
</Suspense>
)
}
async function Runtime() {
await connection()
const rootParams = await getCachedParams()
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return (
<p>
<span id="param">
{rootParams.lang} {rootParams.locale}
</span>{' '}
<span id="random">{data}</span>
</p>
)
}
async function getCachedParams() {
'use cache: private'
return { lang: await lang(), locale: await locale() }
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useCache: true,
rootParams: true,
},
}
export default nextConfig
......@@ -5,7 +5,6 @@ import { createSandbox } from 'development-sandbox'
describe('app-root-param-getters - cache - at runtime', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: join(__dirname, 'fixtures', 'use-cache-runtime'),
skipStart: true,
// this test asserts on build failure logs, which aren't currently observable in `next.cliOutput`.
skipDeployment: true,
})
......@@ -39,19 +38,6 @@ describe('app-root-param-getters - cache - at runtime', () => {
)
})
} else {
beforeAll(async () => {
try {
await next.start()
} catch (err) {
// if (isPPREnabled) {
// throw err
// } else {
// // in PPR/cacheComponents, we expect the build to fail,
// // so we swallow the error and let the tests assert on the logs
// }
}
})
it('should error when using root params within a "use cache" - start', async () => {
await next.render$('/en/us/use-cache')
expect(next.cliOutput).toInclude(
......@@ -68,6 +54,30 @@ describe('app-root-param-getters - cache - at runtime', () => {
}
})
describe('app-root-param-getters - private cache', () => {
const { next, isNextDev } = nextTestSetup({
files: join(__dirname, 'fixtures', 'use-cache-private'),
})
if (isNextDev) {
it('should allow using root params within a "use cache: private" - dev', async () => {
await using sandbox = await createSandbox(
next,
undefined,
'/en/us/use-cache-private'
)
const { session, browser } = sandbox
await session.assertNoRedbox()
expect(await browser.elementById('param').text()).toBe('en us')
})
} else {
it('should allow using root params within a "use cache: private" - start', async () => {
const browser = await next.browser('/en/us/use-cache-private')
expect(await browser.elementById('param').text()).toBe('en us')
})
}
})
describe('app-root-param-getters - cache - at build', () => {
const { next, isNextDev } = nextTestSetup({
files: join(__dirname, 'fixtures', 'use-cache-build'),
......
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