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( ...@@ -1428,6 +1428,9 @@ async function renderToHTMLOrFlightImpl(
// If we encountered any unexpected errors during build we fail the // If we encountered any unexpected errors during build we fail the
// prerendering phase and the build. // prerendering phase and the build.
if (workStore.invalidUsageError) {
throw workStore.invalidUsageError
}
if (response.digestErrorsMap.size) { if (response.digestErrorsMap.size) {
const buildFailingError = response.digestErrorsMap.values().next().value const buildFailingError = response.digestErrorsMap.values().next().value
if (buildFailingError) throw buildFailingError if (buildFailingError) throw buildFailingError
...@@ -1612,6 +1615,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -1612,6 +1615,10 @@ async function renderToHTMLOrFlightImpl(
postponedState postponedState
) )
if (workStore.invalidUsageError) {
throw workStore.invalidUsageError
}
// If we have pending revalidates, wait until they are all resolved. // If we have pending revalidates, wait until they are all resolved.
if ( if (
workStore.pendingRevalidates || workStore.pendingRevalidates ||
......
...@@ -329,11 +329,6 @@ async function createComponentTreeInternal({ ...@@ -329,11 +329,6 @@ async function createComponentTreeInternal({
const isPossiblyPartialResponse = const isPossiblyPartialResponse =
isStaticGeneration && experimental.isRoutePPREnabled === true 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 const LayoutOrPage: React.ComponentType<any> | undefined = layoutOrPageMod
? interopDefault(layoutOrPageMod) ? interopDefault(layoutOrPageMod)
: undefined : undefined
......
import type { AsyncLocalStorage } from 'async_hooks' import type { AsyncLocalStorage } from 'async_hooks'
import type { IncrementalCache } from '../lib/incremental-cache' import type { IncrementalCache } from '../lib/incremental-cache'
import type { DynamicServerError } from '../../client/components/hooks-server-context'
import type { FetchMetrics } from '../base-http' import type { FetchMetrics } from '../base-http'
import type { FallbackRouteParams } from '../request/fallback-params' import type { FallbackRouteParams } from '../request/fallback-params'
import type { DeepReadonly } from '../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../shared/lib/deep-readonly'
...@@ -49,7 +48,14 @@ export interface WorkStore { ...@@ -49,7 +48,14 @@ export interface WorkStore {
dynamicUsageDescription?: string dynamicUsageDescription?: string
dynamicUsageStack?: 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 nextFetchId?: number
pathWasRevalidated?: boolean pathWasRevalidated?: boolean
......
...@@ -462,7 +462,7 @@ export function makeErroringExoticSearchParamsForUseCache( ...@@ -462,7 +462,7 @@ export function makeErroringExoticSearchParamsForUseCache(
typeof prop === 'string' && typeof prop === 'string' &&
(prop === 'then' || !wellKnownProperties.has(prop)) (prop === 'then' || !wellKnownProperties.has(prop))
) { ) {
throwForSearchParamsAccessInUseCache(workStore.route) throwForSearchParamsAccessInUseCache(workStore)
} }
return ReflectAdapter.get(target, prop, receiver) return ReflectAdapter.get(target, prop, receiver)
...@@ -476,13 +476,13 @@ export function makeErroringExoticSearchParamsForUseCache( ...@@ -476,13 +476,13 @@ export function makeErroringExoticSearchParamsForUseCache(
typeof prop === 'string' && typeof prop === 'string' &&
(prop === 'then' || !wellKnownProperties.has(prop)) (prop === 'then' || !wellKnownProperties.has(prop))
) { ) {
throwForSearchParamsAccessInUseCache(workStore.route) throwForSearchParamsAccessInUseCache(workStore)
} }
return ReflectAdapter.has(target, prop) return ReflectAdapter.has(target, prop)
}, },
ownKeys() { ownKeys() {
throwForSearchParamsAccessInUseCache(workStore.route) throwForSearchParamsAccessInUseCache(workStore)
}, },
}) })
......
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external' import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'
import type { WorkStore } from '../app-render/work-async-storage.external'
export function throwWithStaticGenerationBailoutError( export function throwWithStaticGenerationBailoutError(
route: string, route: string,
...@@ -19,10 +20,16 @@ export function throwWithStaticGenerationBailoutErrorWithDynamicError( ...@@ -19,10 +20,16 @@ export function throwWithStaticGenerationBailoutErrorWithDynamicError(
) )
} }
export function throwForSearchParamsAccessInUseCache(route: string): never { export function throwForSearchParamsAccessInUseCache(
throw new Error( workStore: WorkStore
`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` ): 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() { export function isRequestAPICallableInsideAfter() {
......
...@@ -177,6 +177,7 @@ function generateCacheEntryWithCacheContext( ...@@ -177,6 +177,7 @@ function generateCacheEntryWithCacheContext(
return workUnitAsyncStorage.run( return workUnitAsyncStorage.run(
cacheStore, cacheStore,
generateCacheEntryImpl, generateCacheEntryImpl,
workStore,
outerWorkUnitStore, outerWorkUnitStore,
cacheStore, cacheStore,
clientReferenceManifest, clientReferenceManifest,
...@@ -220,6 +221,7 @@ function propagateCacheLifeAndTags( ...@@ -220,6 +221,7 @@ function propagateCacheLifeAndTags(
async function collectResult( async function collectResult(
savedStream: ReadableStream, savedStream: ReadableStream,
workStore: WorkStore,
outerWorkUnitStore: WorkUnitStore | undefined, outerWorkUnitStore: WorkUnitStore | undefined,
innerCacheStore: UseCacheStore, innerCacheStore: UseCacheStore,
startTime: number, startTime: number,
...@@ -248,7 +250,9 @@ async function collectResult( ...@@ -248,7 +250,9 @@ async function collectResult(
let idx = 0 let idx = 0
const bufferStream = new ReadableStream({ const bufferStream = new ReadableStream({
pull(controller) { pull(controller) {
if (idx < buffer.length) { if (workStore.invalidUsageError) {
controller.error(workStore.invalidUsageError)
} else if (idx < buffer.length) {
controller.enqueue(buffer[idx++]) controller.enqueue(buffer[idx++])
} else if (errors.length > 0) { } else if (errors.length > 0) {
// TODO: Should we use AggregateError here? // TODO: Should we use AggregateError here?
...@@ -303,6 +307,7 @@ async function collectResult( ...@@ -303,6 +307,7 @@ async function collectResult(
} }
async function generateCacheEntryImpl( async function generateCacheEntryImpl(
workStore: WorkStore,
outerWorkUnitStore: WorkUnitStore | undefined, outerWorkUnitStore: WorkUnitStore | undefined,
innerCacheStore: UseCacheStore, innerCacheStore: UseCacheStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>, clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>,
...@@ -411,6 +416,7 @@ async function generateCacheEntryImpl( ...@@ -411,6 +416,7 @@ async function generateCacheEntryImpl(
const promiseOfCacheEntry = collectResult( const promiseOfCacheEntry = collectResult(
savedStream, savedStream,
workStore,
outerWorkUnitStore, outerWorkUnitStore,
innerCacheStore, innerCacheStore,
startTime, startTime,
...@@ -508,7 +514,7 @@ export function cache( ...@@ -508,7 +514,7 @@ export function cache(
kind: string, kind: string,
id: string, id: string,
boundArgsLength: number, boundArgsLength: number,
fn: (...args: unknown[]) => Promise<unknown> originalFn: (...args: unknown[]) => Promise<unknown>
) { ) {
const cacheHandler = getCacheHandler(kind) const cacheHandler = getCacheHandler(kind)
if (cacheHandler === undefined) { if (cacheHandler === undefined) {
...@@ -519,7 +525,7 @@ export function cache( ...@@ -519,7 +525,7 @@ export function cache(
const timeoutError = new UseCacheTimeoutError() const timeoutError = new UseCacheTimeoutError()
Error.captureStackTrace(timeoutError, cache) Error.captureStackTrace(timeoutError, cache)
const name = fn.name const name = originalFn.name
const cachedFn = { const cachedFn = {
[name]: async function (...args: any[]) { [name]: async function (...args: any[]) {
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
...@@ -529,6 +535,8 @@ export function cache( ...@@ -529,6 +535,8 @@ export function cache(
) )
} }
let fn = originalFn
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
// Get the clientReferenceManifest while we're still in the outer Context. // Get the clientReferenceManifest while we're still in the outer Context.
...@@ -567,8 +575,6 @@ export function cache( ...@@ -567,8 +575,6 @@ export function cache(
// Overwrite the props to omit $$isPageComponent. // Overwrite the props to omit $$isPageComponent.
args = [{ params, searchParams }] args = [{ params, searchParams }]
const originalFn = fn
fn = { fn = {
[name]: async ({ [name]: async ({
params: serializedParams, 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) => ...@@ -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` `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', () => { describe('use-cache-standalone-search-params', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true, skipDeployment: true,
skipStart: process.env.NEXT_TEST_MODE !== 'dev', skipStart: process.env.NEXT_TEST_MODE !== 'dev',
...@@ -43,29 +43,71 @@ describe('use-cache-standalone-search-params', () => { ...@@ -43,29 +43,71 @@ describe('use-cache-standalone-search-params', () => {
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex)) const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
if (isTurbopack) { expect(errorSource).toMatchInlineSnapshot(`
// TODO(veil): Should have a mapped error source. "app/search-params-used/page.tsx (8:17) @ Page
expect(errorSource).toBe(null)
6 | searchParams: Promise<{ [key: string]: string | string[] | undefined }>
// TODO(veil): Should be a relative filename. 7 | }) {
expect(cliOutput).toContain(`${expectedErrorMessage} > 8 | const param = (await searchParams).foo
at Page (file:/`) | ^
} else { 9 |
expect(errorSource).toMatchInlineSnapshot(` 10 | return <p>param: {param}</p>
"app/search-params-used/page.tsx (8:17) @ Page 11 | }"
`)
6 | searchParams: Promise<{ [key: string]: string | string[] | undefined }>
7 | }) { expect(cliOutput).toContain(`${expectedErrorMessage}
> 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)`) 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', () => { ...@@ -93,6 +135,10 @@ describe('use-cache-standalone-search-params', () => {
getExpectedErrorMessage('/search-params-used') getExpectedErrorMessage('/search-params-used')
) )
expect(cliOutput).toInclude(
getExpectedErrorMessage('/search-params-caught')
)
expect(cliOutput).not.toInclude( expect(cliOutput).not.toInclude(
getExpectedErrorMessage('/search-params-unused') 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