Unverified Commit 7fc1a200 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

fix: request APIs in promises passed to after() in actions/handlers (#94964)

Fixes a bug where Route Handlers and Server Actions were prevented from
calling `headers()` (and other request APIs) if
- the call happened after the response is finished
- the call *did not happen* inside an after-callback
generally, this happens when you pass a promise to after.
```ts
const longRunning = () => {
  // assume this resolves after the response
  await new Promise((resolve) => setTimeout(resolve, 100))
  // response is done
  after(() => {
    await headers() // ❌ should be allowed, but throws
  })
}

after(longRunning()) // or waitUntil, doesn't matter
```

The logic we used in the check was incorrect and assumed that an
`afterTaskStore` was present, but we can only wrap callbacks in this ALS
- we cannot change the async context of already-running promises.

One noteworthy change is that i had to exit `actionAsyncStorage` when we
do a render after the server action. Otherwise the checks in
`isRequestApiAllowedInCurrentPhase` might believe that they're still in
a server action when they aren't.
parent d538cfb7
......@@ -1366,5 +1366,10 @@
"1365": "Expected a dev tiered cache handler for kind \"%s\".",
"1366": "Turbopack build failed with %s %s:\\n%s",
"1367": "createServerParamsForRoute should not be called in runtime prerenders.",
"1368": "An onClose call failed, which means after() can't work correctly."
"1368": "An onClose call failed, which means after() can't work correctly.",
"1369": "Route %s used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1370": "Route %s used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1371": "Route %s used \\`io()\\` inside \\`after()\\`. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1372": "Route %s used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1373": "Route %s used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after"
}
......@@ -1171,15 +1171,17 @@ export async function handleAction({
return {
type: 'done',
result: await generateFlight(req, ctx, requestStore, {
actionResult: Promise.resolve(actionResult),
skipPageRendering,
temporaryReferences,
waitUntil:
maybeRevalidatesPromise === false
? undefined
: maybeRevalidatesPromise,
}),
result: await actionAsyncStorage.exit(() =>
generateFlight(req, ctx, requestStore, {
actionResult: Promise.resolve(actionResult),
skipPageRendering,
temporaryReferences,
waitUntil:
maybeRevalidatesPromise === false
? undefined
: maybeRevalidatesPromise,
})
),
}
} else {
// TODO: this shouldn't be reachable, because all non-fetch codepaths return early.
......
......@@ -13,7 +13,7 @@ import {
makeHangingPromise,
makeDevtoolsIOAwarePromise,
} from '../dynamic-rendering-utils'
import { isRequestAPICallableInsideAfter } from './utils'
import { isRequestApiAllowedInCurrentPhase } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { RenderStage } from '../app-render/staged-rendering'
import { InvariantError } from '../../shared/lib/invariant-error'
......@@ -29,13 +29,9 @@ export function connection(): Promise<void> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore) {
if (
workUnitStore &&
workUnitStore.phase === 'after' &&
!isRequestAPICallableInsideAfter()
) {
if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {
throw new Error(
`Route ${workStore.route} used \`connection()\` inside \`after()\`. The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
`Route ${workStore.route} used \`connection()\` inside \`after()\` while rendering. The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
......
......@@ -27,7 +27,7 @@ import {
getSessionDataStage,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestAPICallableInsideAfter } from './utils'
import { isRequestApiAllowedInCurrentPhase } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
......@@ -38,14 +38,9 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore) {
if (
workUnitStore &&
workUnitStore.phase === 'after' &&
!isRequestAPICallableInsideAfter()
) {
if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {
throw new Error(
// TODO(after): clarify that this only applies to pages?
`Route ${workStore.route} used \`cookies()\` inside \`after()\`. This is not supported. If you need this data inside an \`after()\` callback, use \`cookies()\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
`Route ${workStore.route} used \`cookies()\` inside \`after()\` while rendering. This is not supported. If you need this data inside an \`after()\` callback, use \`cookies()\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
......
......@@ -25,7 +25,7 @@ import {
getSessionDataStage,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestAPICallableInsideAfter } from './utils'
import { isRequestApiAllowedInCurrentPhase } from './utils'
import { applyOwnerStack } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
......@@ -45,13 +45,9 @@ export function headers(): Promise<ReadonlyHeaders> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore) {
if (
workUnitStore &&
workUnitStore.phase === 'after' &&
!isRequestAPICallableInsideAfter()
) {
if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {
throw new Error(
`Route ${workStore.route} used \`headers()\` inside \`after()\`. This is not supported. If you need this data inside an \`after()\` callback, use \`headers()\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
`Route ${workStore.route} used \`headers()\` inside \`after()\` while rendering. This is not supported. If you need this data inside an \`after()\` callback, use \`headers()\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
......
......@@ -6,6 +6,7 @@ import {
} from '../dynamic-rendering-utils'
import { RenderStage } from '../app-render/staged-rendering'
import { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'
import { isRequestApiAllowedInCurrentPhase } from './utils'
// A fulfilled thenable that React can unwrap synchronously via `use()` without
// ever suspending. Reusing a single instance avoids allocating on every call.
......@@ -29,6 +30,11 @@ export function io(): Promise<void> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore && workUnitStore) {
if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {
throw new Error(
`Route ${workStore.route} used \`io()\` inside \`after()\` while rendering. The \`io()\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
switch (workUnitStore.type) {
case 'request':
// For dev renders we instrument the promise so it will show up in
......
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { actionAsyncStorage } from '../app-render/action-async-storage.external'
import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'
import type { WorkStore } from '../app-render/work-async-storage.external'
import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'
export function throwWithStaticGenerationBailoutErrorWithDynamicError(
route: string,
......@@ -25,7 +27,42 @@ export function throwForSearchParamsAccessInUseCache(
throw error
}
export function isRequestAPICallableInsideAfter() {
const afterTaskStore = afterTaskAsyncStorage.getStore()
return afterTaskStore?.rootTaskSpawnPhase === 'action'
export function isRequestApiAllowedInCurrentPhase(
workUnitStore: WorkUnitStore
): boolean {
switch (workUnitStore.phase) {
case 'action':
case 'render': {
// The request is still in progress. The API may be disallowed for other reasons,
// but not because of phase.
return true
}
case 'after': {
// The request has finished.
// If we're in a Route Handler or a Server Action,
// request APIs can be called everywhere, even in after().
const actionStore = actionAsyncStorage.getStore()
if (actionStore && (actionStore.isAppRoute || actionStore.isAction)) {
return true
}
const afterTaskStore = afterTaskAsyncStorage.getStore()
if (afterTaskStore) {
// We're in an `after` callback. Request APIs are callable if
// the `after()` call happened in an action phase:
// - in a Route Handler
// - in a Server Action's body (but not the render after)
//
// TODO(after): Is it even possible to have `phase === 'action'` but no `actionStore`?
// We should revisit this setup and simplify this.
return afterTaskStore.rootTaskSpawnPhase === 'action'
}
// Otherwise, we must be in a page, in the `after` phase.
// We don't allow calling request APIs here because we'd miss
// them during prerendering and wouldn't know that the page is dynamic.
return false
}
}
}
import { cookies, headers } from 'next/headers'
import { after, connection } from 'next/server'
import { io } from 'next/cache'
const apis = {
headers,
cookies,
connection,
io,
}
export const REQUEST_API_NAMES = Object.keys(apis)
export function testApiInPromisePassedToAfter(
context: string,
apiName: keyof typeof apis | (string & {})
) {
if (!(apiName in apis)) {
throw new Error(`Invalid api: ${apiName}`)
}
const apiFn = apis[apiName as keyof typeof apis]
const longRunning = async () => {
await new Promise((resolve) => setTimeout(resolve, 1000))
console.log(`${context} :: ${apiName} :: after delay`)
// Check calling the api directly
try {
await apiFn()
console.log(`${context} :: ${apiName} :: promise :: ok`)
} catch (err) {
console.log(`${context} :: ${apiName} :: promise :: error:`, err)
}
// Check calling the api from a nested after
after(async () => {
try {
await apiFn()
console.log(`${context} :: ${apiName} :: nested after :: ok`)
} catch (err) {
console.log(`${context} :: ${apiName} :: nested after :: error:`, err)
}
console.log(`${context} :: ${apiName} :: finished`)
})
}
console.log(`${context} :: ${apiName} :: starting`)
const promise = longRunning()
after(promise)
}
import { cookies } from 'next/headers'
import { testApiInPromisePassedToAfter, REQUEST_API_NAMES } from '../common'
import { Suspense } from 'react'
const COOKIE = 'api-name'
async function action(apiName: string) {
'use server'
const cookieStore = await cookies()
// The page only runs the test when the cookie is set,
// so it won't run it on initial load, only when
// we're rerendering after an action.
cookieStore.set(COOKIE, apiName)
}
export default async function Page() {
return (
<main>
<Suspense>
<TestAfterIfCookieSet />
</Suspense>
{REQUEST_API_NAMES.map((apiName) => (
<form data-api-name={apiName} action={action.bind(null, apiName)}>
<button type="submit">Submit - {apiName}</button>
</form>
))}
</main>
)
}
async function TestAfterIfCookieSet() {
const cookieStore = await cookies()
const apiName = cookieStore.get(COOKIE)?.value
if (apiName !== undefined) {
testApiInPromisePassedToAfter('render after action', apiName)
}
return null
}
import { testApiInPromisePassedToAfter } from '../common'
import { Suspense } from 'react'
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ apiName?: string }>
}) {
return (
<main>
<Suspense>
<TestApiInAfter searchParams={searchParams} />
</Suspense>
</main>
)
}
async function TestApiInAfter({
searchParams,
}: {
searchParams: Promise<{ apiName?: string }>
}) {
const { apiName } = await searchParams
testApiInPromisePassedToAfter('render', apiName!)
return null
}
import { testApiInPromisePassedToAfter } from '../common'
export async function GET(request: Request) {
const apiName = new URL(request.url).searchParams.get('api') as string
testApiInPromisePassedToAfter('route', apiName)
return new Response('hello')
}
import { testApiInPromisePassedToAfter, REQUEST_API_NAMES } from '../common'
async function action(apiName: string) {
'use server'
testApiInPromisePassedToAfter('action', apiName)
}
export default async function Page() {
return (
<main>
{REQUEST_API_NAMES.map((apiName) => (
<form data-api-name={apiName} action={action.bind(null, apiName)}>
<button type="submit">Submit - {apiName}</button>
</form>
))}
</main>
)
}
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