Unverified Commit d7aef6f9 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Ensure `searchParams` access in `"use cache"` triggers error when caught (#77838)

Accessing search params in `"use cache"` functions is not allowed. We need to make sure that a build or dev error is still triggered even when the `searchParams` access is wrapped in a try/catch block.

This also fixes a bug where the errors were not correctly source-mapped with Turbopack.

related: #75662
closes NAR-86
parent 65c3c845
......@@ -1428,6 +1428,9 @@ async function renderToHTMLOrFlightImpl(
// If we encountered any unexpected errors during build we fail the
// prerendering phase and the build.
if (workStore.invalidUsageError) {
throw workStore.invalidUsageError
}
if (response.digestErrorsMap.size) {
const buildFailingError = response.digestErrorsMap.values().next().value
if (buildFailingError) throw buildFailingError
......@@ -1612,6 +1615,10 @@ async function renderToHTMLOrFlightImpl(
postponedState
)
if (workStore.invalidUsageError) {
throw workStore.invalidUsageError
}
// If we have pending revalidates, wait until they are all resolved.
if (
workStore.pendingRevalidates ||
......
......@@ -329,11 +329,6 @@ async function createComponentTreeInternal({
const isPossiblyPartialResponse =
isStaticGeneration && experimental.isRoutePPREnabled === true
// If there's a dynamic usage error attached to the store, throw it.
if (workStore.dynamicUsageErr) {
throw workStore.dynamicUsageErr
}
const LayoutOrPage: React.ComponentType<any> | undefined = layoutOrPageMod
? interopDefault(layoutOrPageMod)
: undefined
......
import type { AsyncLocalStorage } from 'async_hooks'
import type { IncrementalCache } from '../lib/incremental-cache'
import type { DynamicServerError } from '../../client/components/hooks-server-context'
import type { FetchMetrics } from '../base-http'
import type { FallbackRouteParams } from '../request/fallback-params'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
......@@ -49,7 +48,14 @@ export interface WorkStore {
dynamicUsageDescription?: string
dynamicUsageStack?: string
dynamicUsageErr?: DynamicServerError
/**
* Invalid usage errors might be caught in userland. We attach them to the
* work store to ensure we can still fail the build or dev render.
*/
// TODO: Collect an array of errors, and throw as AggregateError when
// `serializeError` and the Dev Overlay support it.
invalidUsageError?: Error
nextFetchId?: number
pathWasRevalidated?: boolean
......
......@@ -462,7 +462,7 @@ export function makeErroringExoticSearchParamsForUseCache(
typeof prop === 'string' &&
(prop === 'then' || !wellKnownProperties.has(prop))
) {
throwForSearchParamsAccessInUseCache(workStore.route)
throwForSearchParamsAccessInUseCache(workStore)
}
return ReflectAdapter.get(target, prop, receiver)
......@@ -476,13 +476,13 @@ export function makeErroringExoticSearchParamsForUseCache(
typeof prop === 'string' &&
(prop === 'then' || !wellKnownProperties.has(prop))
) {
throwForSearchParamsAccessInUseCache(workStore.route)
throwForSearchParamsAccessInUseCache(workStore)
}
return ReflectAdapter.has(target, prop)
},
ownKeys() {
throwForSearchParamsAccessInUseCache(workStore.route)
throwForSearchParamsAccessInUseCache(workStore)
},
})
......
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'
import type { WorkStore } from '../app-render/work-async-storage.external'
export function throwWithStaticGenerationBailoutError(
route: string,
......@@ -19,10 +20,16 @@ export function throwWithStaticGenerationBailoutErrorWithDynamicError(
)
}
export function throwForSearchParamsAccessInUseCache(route: string): never {
throw new Error(
`Route ${route} used "searchParams" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "searchParams" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
export function throwForSearchParamsAccessInUseCache(
workStore: WorkStore
): never {
const error = new Error(
`Route ${workStore.route} used "searchParams" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "searchParams" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
workStore.invalidUsageError ??= error
throw error
}
export function isRequestAPICallableInsideAfter() {
......
......@@ -177,6 +177,7 @@ function generateCacheEntryWithCacheContext(
return workUnitAsyncStorage.run(
cacheStore,
generateCacheEntryImpl,
workStore,
outerWorkUnitStore,
cacheStore,
clientReferenceManifest,
......@@ -220,6 +221,7 @@ function propagateCacheLifeAndTags(
async function collectResult(
savedStream: ReadableStream,
workStore: WorkStore,
outerWorkUnitStore: WorkUnitStore | undefined,
innerCacheStore: UseCacheStore,
startTime: number,
......@@ -248,7 +250,9 @@ async function collectResult(
let idx = 0
const bufferStream = new ReadableStream({
pull(controller) {
if (idx < buffer.length) {
if (workStore.invalidUsageError) {
controller.error(workStore.invalidUsageError)
} else if (idx < buffer.length) {
controller.enqueue(buffer[idx++])
} else if (errors.length > 0) {
// TODO: Should we use AggregateError here?
......@@ -303,6 +307,7 @@ async function collectResult(
}
async function generateCacheEntryImpl(
workStore: WorkStore,
outerWorkUnitStore: WorkUnitStore | undefined,
innerCacheStore: UseCacheStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>,
......@@ -411,6 +416,7 @@ async function generateCacheEntryImpl(
const promiseOfCacheEntry = collectResult(
savedStream,
workStore,
outerWorkUnitStore,
innerCacheStore,
startTime,
......@@ -508,7 +514,7 @@ export function cache(
kind: string,
id: string,
boundArgsLength: number,
fn: (...args: unknown[]) => Promise<unknown>
originalFn: (...args: unknown[]) => Promise<unknown>
) {
const cacheHandler = getCacheHandler(kind)
if (cacheHandler === undefined) {
......@@ -519,7 +525,7 @@ export function cache(
const timeoutError = new UseCacheTimeoutError()
Error.captureStackTrace(timeoutError, cache)
const name = fn.name
const name = originalFn.name
const cachedFn = {
[name]: async function (...args: any[]) {
const workStore = workAsyncStorage.getStore()
......@@ -529,6 +535,8 @@ export function cache(
)
}
let fn = originalFn
const workUnitStore = workUnitAsyncStorage.getStore()
// Get the clientReferenceManifest while we're still in the outer Context.
......@@ -567,8 +575,6 @@ export function cache(
// Overwrite the props to omit $$isPageComponent.
args = [{ params, searchParams }]
const originalFn = fn
fn = {
[name]: async ({
params: serializedParams,
......
'use cache'
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
let param: string | string[] | undefined
try {
param = (await searchParams).foo
} catch {}
return <p>param: {param}</p>
}
......@@ -11,7 +11,7 @@ const getExpectedErrorMessage = (route: string) =>
`Error: Route ${route} used "searchParams" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "searchParams" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
describe('use-cache-standalone-search-params', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: process.env.NEXT_TEST_MODE !== 'dev',
......@@ -43,29 +43,71 @@ describe('use-cache-standalone-search-params', () => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
if (isTurbopack) {
// TODO(veil): Should have a mapped error source.
expect(errorSource).toBe(null)
// TODO(veil): Should be a relative filename.
expect(cliOutput).toContain(`${expectedErrorMessage}
at Page (file:/`)
} else {
expect(errorSource).toMatchInlineSnapshot(`
"app/search-params-used/page.tsx (8:17) @ Page
6 | searchParams: Promise<{ [key: string]: string | string[] | undefined }>
7 | }) {
> 8 | const param = (await searchParams).foo
| ^
9 |
10 | return <p>param: {param}</p>
11 | }"
`)
expect(cliOutput).toContain(`${expectedErrorMessage}
expect(errorSource).toMatchInlineSnapshot(`
"app/search-params-used/page.tsx (8:17) @ Page
6 | searchParams: Promise<{ [key: string]: string | string[] | undefined }>
7 | }) {
> 8 | const param = (await searchParams).foo
| ^
9 |
10 | return <p>param: {param}</p>
11 | }"
`)
expect(cliOutput).toContain(`${expectedErrorMessage}
at Page (app/search-params-used/page.tsx:8:17)`)
}
})
})
describe('when searchParams are caught inside of "use cache"', () => {
beforeAll(() => {
route = '/search-params-caught'
})
it('should show an error', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser(`${route}?foo=1`)
await assertHasRedbox(browser)
const errorDescription = await getRedboxDescription(browser)
const errorSource = await getRedboxSource(browser)
const expectedErrorMessage = getExpectedErrorMessage(route)
expect(errorDescription).toBe(expectedErrorMessage)
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(errorSource).toMatchInlineSnapshot(`
"app/search-params-caught/page.tsx (11:5) @ Page
9 |
10 | try {
> 11 | param = (await searchParams).foo
| ^
12 | } catch {}
13 |
14 | return <p>param: {param}</p>"
`)
expect(cliOutput).toContain(`${expectedErrorMessage}
at Page (app/search-params-caught/page.tsx:11:4)`)
})
it('should also show an error after the second reload', async () => {
// There was an obscure bug that lead to the error not being triggered
// anymore starting with the third request. We test this scenario
// explicitly to ensure we won't regress.
const browser = await next.browser(`${route}?foo=1`)
await browser.refresh()
await browser.refresh()
await assertHasRedbox(browser)
const errorDescription = await getRedboxDescription(browser)
expect(errorDescription).toBe(getExpectedErrorMessage(route))
})
})
......@@ -93,6 +135,10 @@ describe('use-cache-standalone-search-params', () => {
getExpectedErrorMessage('/search-params-used')
)
expect(cliOutput).toInclude(
getExpectedErrorMessage('/search-params-caught')
)
expect(cliOutput).not.toInclude(
getExpectedErrorMessage('/search-params-unused')
)
......
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