Unverified Commit 4e0b1125 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Improve error handling for `headers`/`cookies`/`draftMode` in `'use cache'` (#81716)

This ensures that we show a proper error with an error stack
(potentially source-mapped) when accessing
`headers`/`cookies`/`draftMode` in `'use cache'`, even when caught in
user-land code. For `searchParams` (currently triggering a timeout
error) we'll need a slightly different solution, which will be handled
in a future PR.

The approach chosen here is somewhat temporary, as we'd like to
implement compile-time errors instead for accessing any kind of request
data in `'use cache'` functions. However, this would require a larger
change to our bundlers.

closes NAR-201
parent 63090e20
......@@ -135,6 +135,7 @@ import {
PreludeState,
consumeDynamicAccess,
type DynamicAccess,
logDisallowedDynamicError,
} from './dynamic-rendering'
import {
getClientComponentLoaderMetrics,
......@@ -1456,7 +1457,8 @@ async function renderToHTMLOrFlightImpl(
// If we encountered any unexpected errors during build we fail the
// prerendering phase and the build.
if (workStore.invalidDynamicUsageError) {
throw workStore.invalidDynamicUsageError
logDisallowedDynamicError(workStore, workStore.invalidDynamicUsageError)
throw new StaticGenBailoutError()
}
if (response.digestErrorsMap.size) {
const buildFailingError = response.digestErrorsMap.values().next().value
......@@ -3047,7 +3049,8 @@ async function prerenderToStream(
// We don't need to continue the prerender process if we already
// detected invalid dynamic usage in the initial prerender phase.
if (workStore.invalidDynamicUsageError) {
throw workStore.invalidDynamicUsageError
logDisallowedDynamicError(workStore, workStore.invalidDynamicUsageError)
throw new StaticGenBailoutError()
}
let initialServerResult
......
......@@ -678,7 +678,10 @@ export enum PreludeState {
Errored = 2,
}
function logDisallowedDynamicError(workStore: WorkStore, error: Error): void {
export function logDisallowedDynamicError(
workStore: WorkStore,
error: Error
): void {
console.error(error)
if (!workStore.dev) {
......@@ -700,11 +703,6 @@ export function throwIfDisallowedDynamic(
dynamicValidation: DynamicValidationState,
serverDynamic: DynamicTrackingState
): void {
if (workStore.invalidDynamicUsageError) {
logDisallowedDynamicError(workStore, workStore.invalidDynamicUsageError)
throw new StaticGenBailoutError()
}
if (prelude !== PreludeState.Full) {
if (dynamicValidation.hasSuspenseAboveBody) {
// This route has opted into allowing fully dynamic rendering
......
......@@ -81,9 +81,12 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache':
throw new Error(
const error = new Error(
`Route ${workStore.route} used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" 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.captureStackTrace(error, cookies)
workStore.invalidDynamicUsageError ??= error
throw error
case 'unstable-cache':
throw new Error(
`Route ${workStore.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
......
......@@ -229,13 +229,13 @@ class DraftMode {
public enable() {
// We have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
trackDynamicDraftMode('draftMode().enable()')
trackDynamicDraftMode('draftMode().enable()', this.enable)
if (this._provider !== null) {
this._provider.enable()
}
}
public disable() {
trackDynamicDraftMode('draftMode().disable()')
trackDynamicDraftMode('draftMode().disable()', this.disable)
if (this._provider !== null) {
this._provider.disable()
}
......@@ -286,44 +286,50 @@ function createDraftModeAccessError(
)
}
function trackDynamicDraftMode(expression: string) {
const store = workAsyncStorage.getStore()
function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (store) {
if (workStore) {
// We have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
if (workUnitStore?.phase === 'after') {
throw new Error(
`Route ${store.route} used "${expression}" inside \`after\`. The enabled status of draftMode can be read inside \`after\` but you cannot enable or disable draftMode. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
`Route ${workStore.route} used "${expression}" inside \`after\`. The enabled status of draftMode can be read inside \`after\` but you cannot enable or disable draftMode. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
if (store.dynamicShouldError) {
if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError(
`Route ${store.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
case 'cache': {
const error = new Error(
`Route ${workStore.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, constructorOpt)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache':
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
`Route ${workStore.route} used "${expression}" inside a function cached with "unstable_cache(...)". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'prerender':
case 'prerender': {
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`
`Route ${workStore.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`
)
return abortAndThrowOnSynchronousRequestDataAccess(
store.route,
workStore.route,
expression,
error,
workUnitStore
)
}
case 'prerender-client':
const exportName = '`draftMode`'
throw new InvariantError(
......@@ -331,7 +337,7 @@ function trackDynamicDraftMode(expression: string) {
)
case 'prerender-ppr':
return postponeWithTracking(
store.route,
workStore.route,
expression,
workUnitStore.dynamicTracking
)
......@@ -339,10 +345,10 @@ function trackDynamicDraftMode(expression: string) {
workUnitStore.revalidate = 0
const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
`Route ${workStore.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
workStore.dynamicUsageDescription = expression
workStore.dynamicUsageStack = err.stack
throw err
case 'request':
......
......@@ -79,9 +79,12 @@ export function headers(): Promise<ReadonlyHeaders> {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache':
throw new Error(
const error = new Error(
`Route ${workStore.route} used "headers" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" 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.captureStackTrace(error, headers)
workStore.invalidDynamicUsageError ??= error
throw error
case 'unstable-cache':
throw new Error(
`Route ${workStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { cookies } from 'next/headers'
export default async function Page() {
return (
<>
<p>
This page accesses `cookies()` in `'use cache'`, which triggers an
error.
</p>
<CookiesReadingComponent />
</>
)
}
async function CookiesReadingComponent() {
'use cache'
// Reading cookies in a non-private cache context is not allowed. We're
// try/catching here to ensure that this error is shown even when it's caught
// in userland.
try {
await cookies()
} catch {}
return null
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { draftMode } from 'next/headers'
export default async function Page() {
return (
<>
<p>
This page enables draft mode in `'use cache'`, which triggers an error.
</p>
<DraftModeEnablingComponent />
</>
)
}
async function DraftModeEnablingComponent() {
'use cache'
// Enabling draft mode in a cache context is not allowed. We're try/catching
// here to ensure that this error is shown even when it's caught in userland.
try {
;(await draftMode()).enable()
} catch {}
return null
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { headers } from 'next/headers'
export default async function Page() {
return (
<>
<p>
This page accesses `headers()` in `'use cache'`, which triggers an
error.
</p>
<HeadersReadingComponent />
</>
)
}
async function HeadersReadingComponent() {
'use cache'
// Reading headers in a cache context is not allowed. We're try/catching here
// to ensure that this error is shown even when it's caught in userland.
try {
await headers()
} catch {}
return null
}
import { nextTestSetup } from 'e2e-utils'
import escapeStringRegexp from 'escape-string-regexp'
import {
getRedboxDescription,
getRedboxSource,
......@@ -323,11 +324,16 @@ describe('use-cache-hanging-inputs', () => {
})
})
} else {
// TODO: Be more precise about the expected error messages and stacks.
it('should fail the build with errors after a timeout', async () => {
const { cliOutput } = await next.build()
expect(cliOutput).toInclude(
createExpectedBuildErrorMessage('/error', 'kaputt!')
expect(cliOutput).toInclude(createExpectedBuildErrorMessage('/error'))
expect(cliOutput).toInclude('Error: kaputt!')
expect(cliOutput).toIncludeRepeated(
escapeStringRegexp(expectedTimeoutErrorMessage),
6
)
expect(cliOutput).toInclude(
......@@ -357,10 +363,6 @@ describe('use-cache-hanging-inputs', () => {
}
})
function createExpectedBuildErrorMessage(
pathname: string,
errorMessage: string = expectedTimeoutErrorMessage
) {
return `Error occurred prerendering page "${pathname}". Read more: https://nextjs.org/docs/messages/prerender-error
Error: ${errorMessage}`
function createExpectedBuildErrorMessage(pathname: string) {
return `Error occurred prerendering page "${pathname}". Read more: https://nextjs.org/docs/messages/prerender-error`
}
'use client'
import { Component, Suspense } from 'react'
export default class ErrorBoundary extends Component<
{ id: string; children: React.ReactNode },
{ message: null | string }
> {
state = { message: null }
static getDerivedStateFromError(error: any) {
return { message: error.message }
}
render() {
let content
if (this.state.message !== null) {
content = this.state.message
} else {
content = this.props.children
}
return (
<p id={this.props.id}>
<Suspense>{content}</Suspense>
</p>
)
}
}
import ErrorBoundary from './error-boundary'
import { cookies } from 'next/headers'
import { currentUser, currentReferer, isEditing } from './util'
async function Cookie() {
'use cache'
return <div>User: {currentUser()}</div>
}
async function Header() {
'use cache'
return <div>Referer: {currentReferer()}</div>
}
async function DraftMode() {
'use cache'
return <div>Editing: {isEditing()}</div>
}
export default async function Page() {
await cookies()
return (
<div>
<ErrorBoundary id="cookies">
<Cookie />
</ErrorBoundary>
<ErrorBoundary id="headers">
<Header />
</ErrorBoundary>
<ErrorBoundary id="draft-mode">
<DraftMode />
</ErrorBoundary>
</div>
)
}
import { cookies, headers, draftMode } from 'next/headers'
export async function currentUser() {
return (await cookies()).get('user')?.value
}
export async function currentReferer() {
return (await headers()).get('referer')
}
export async function isEditing() {
return String((await draftMode()).isEnabled)
}
'use cache'
import { cookies, draftMode } from 'next/headers'
import { Button } from './button'
......@@ -24,7 +22,14 @@ async function getCachedValue(
return [date.toISOString(), fn]
}
export default async function Page() {
export default async function Page({
params,
}: {
params: Promise<{ mode: string }>
}) {
'use cache'
const { mode } = await params
const offset = 1000
const cachedClosure = async () => {
......@@ -36,14 +41,8 @@ export default async function Page() {
// Accessing request-scoped data in "use cache" should not be allowed, even if
// draft mode is enabled. We expect the access to throw.
let isAccessingRequestScopedDataAllowedInUseCache = isEnabled
if (isAccessingRequestScopedDataAllowedInUseCache) {
try {
await cookies()
} catch {
isAccessingRequestScopedDataAllowedInUseCache = false
}
if (isEnabled && mode === 'with-cookies') {
await cookies()
}
const [cachedValue, passthroughFn] = await getCachedValue(
......@@ -71,11 +70,12 @@ export default async function Page() {
>
<p id="top-level">{cachedValue}</p>
<p id="closure">{await cachedClosure()}</p>
<p id="is-accessing-request-scoped-data-allowed-in-use-cache">
{isAccessingRequestScopedDataAllowedInUseCache.toString()}
</p>
<p>{passthroughFn()}</p>
<Button id="toggle">{isEnabled ? 'Disable' : 'Enable'} Draft Mode</Button>
</form>
)
}
export function generateStaticParams() {
return [{ mode: 'with-cookies' }, { mode: 'without-cookies' }]
}
......@@ -134,37 +134,6 @@ describe('use-cache', () => {
)
})
it('should error when cookies/headers/draftMode is used inside "use cache"', async () => {
const browser = await next.browser('/errors')
await retry(async () => {
expect(await browser.elementById('cookies').text()).toContain(
isNextDev
? 'Route /errors used "cookies" inside "use cache".'
: GENERIC_RSC_ERROR
)
expect(await browser.elementById('headers').text()).toContain(
isNextDev
? 'Route /errors used "headers" inside "use cache".'
: GENERIC_RSC_ERROR
)
})
expect(await browser.elementById('draft-mode').text()).toContain(
'Editing: false'
)
// CLI assertions are skipped in deploy mode because `next.cliOutput` will only contain build-time logs.
if (!isNextDeploy) {
expect(next.cliOutput).toContain(
'Route /errors used "cookies" inside "use cache". '
)
expect(next.cliOutput).toContain(
'Route /errors used "headers" inside "use cache". '
)
}
})
it('should cache results in route handlers', async () => {
const response = await next.fetch('/api')
const { rand1, rand2 } = await response.json()
......@@ -515,7 +484,8 @@ describe('use-cache', () => {
'/cache-tag',
'/directive-in-node-modules/with-handler',
'/directive-in-node-modules/without-handler',
'/draft-mode',
'/draft-mode/with-cookies',
'/draft-mode/without-cookies',
'/form',
'/imported-from-client',
'/logs',
......@@ -771,46 +741,60 @@ describe('use-cache', () => {
})
describe('should not read nor write cached data when draft mode is enabled', () => {
if (isNextDeploy) {
// Wait for the background revalidation after the deployment to settle.
beforeAll(async () => {
const browser = await next.browser('/draft-mode')
try {
const initialTopLevelValue = await browser
.elementById('top-level')
.text()
await retry(async () => {
await browser.refresh()
expect(await browser.elementById('top-level').text()).not.toBe(
initialTopLevelValue
)
})
} finally {
// we're not in a test, so the browser won't get cleaned up automatically.
await browser.close()
}
})
}
it.each([
{ description: 'js enabled', disableJavaScript: false },
{ description: 'js disabled', disableJavaScript: true },
])('$description', async ({ disableJavaScript }) => {
const browser = await next.browser('/draft-mode', {
{
description: 'js enabled, with cookies',
disableJavaScript: false,
mode: 'with-cookies',
},
{
description: 'js disabled, with cookies',
disableJavaScript: true,
mode: 'with-cookies',
},
{
description: 'js enabled, without cookies',
disableJavaScript: false,
mode: 'without-cookies',
},
{
description: 'js disabled, without cookies',
disableJavaScript: true,
mode: 'without-cookies',
},
])('$description', async ({ disableJavaScript, mode }) => {
const pathname = `/draft-mode/${mode}`
const browser = await next.browser(pathname, {
// This test relies on a server action to set draft mode.
// To ensure that it works for both fetch actions and MPA actions,
// we test it with javascript disabled too.
// (this is because of a bug where draft mode status was not correctly propagated to the workStore for MPA actions)
disableJavaScript,
pushErrorAsConsoleLog: true,
})
if (isNextDeploy) {
// Wait for the background revalidation after the deployment to settle.
const initialTopLevelValue = await browser
.elementById('top-level')
.text()
await retry(async () => {
await browser.refresh()
expect(await browser.elementById('top-level').text()).not.toBe(
initialTopLevelValue
)
})
}
const refreshAfterServerAction = async () => {
if (disableJavaScript) {
// browser.refresh() seems to automatically resubmit POST requests,
// so if we submitted an MPA action, it'll trigger the action again,
// which in this case will toggle draftMode again.
await browser.get(new URL('/draft-mode', next.url).href)
await browser.get(new URL(pathname, next.url).href)
} else {
await browser.refresh()
}
......@@ -835,7 +819,29 @@ describe('use-cache', () => {
initialClosureValue
)
// Enable draft mode.
await browser.elementByCss('button#toggle').click()
// When reading cookies, we expect an error.
// TODO: Ideally this would be a compile-time error.
if (mode === 'with-cookies') {
return retry(async () => {
const logs = await browser.log()
const expectedErrorMessage = disableJavaScript
? 'Failed to load resource: the server responded with a status of 500 (Internal Server Error)'
: isNextDev
? 'Route /draft-mode/[mode] used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" 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'
: GENERIC_RSC_ERROR
expect(logs).toMatchObject(
expect.arrayContaining([
{ source: 'error', message: expectedErrorMessage },
])
)
})
}
await browser.waitForElementByCss('button#toggle:enabled')
expect(await browser.elementByCss('button#toggle').text()).toBe(
......@@ -862,13 +868,6 @@ describe('use-cache', () => {
newClosureValue
)
// Accessing request-scoped data should still not be allowed.
expect(
await browser
.elementById('is-accessing-request-scoped-data-allowed-in-use-cache')
.text()
).toBe('false')
await browser.elementByCss('button#toggle').click()
await browser.waitForElementByCss('button#toggle:enabled')
......
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