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>
)
}
/* eslint-env jest */
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { REQUEST_API_NAMES } from './app/request-apis-in-promise/common'
describe('nextjs APIs in after()', () => {
const { next, skipped, isNextDev } = nextTestSetup({
......@@ -33,20 +34,10 @@ describe('nextjs APIs in after()', () => {
} else {
buildLogs = '(no build logs in dev)'
}
await next.start()
await next.start({ skipBuild: true })
})
describe('request APIs inside after()', () => {
// TODO(after): test unawaited calls, like this
//
// export default function Page() {
// const promise = headers()
// after(async () => {
// const headerStore = await promise
// })
// return null
// }
it('cannot be called in a dynamic page', async () => {
const path = '/request-apis/page-dynamic'
await next.render(path)
......@@ -55,17 +46,17 @@ describe('nextjs APIs in after()', () => {
expect(logs).not.toContain(`[${path}] headers(): ok`)
expect(logs).toContain(
`[${path}] headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\`. This is not supported.`
`[${path}] headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\` while rendering. This is not supported.`
)
expect(logs).not.toContain(`[${path}] cookies(): ok`)
expect(logs).toContain(
`[${path}] cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\`. This is not supported.`
`[${path}] cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\` while rendering. This is not supported.`
)
expect(logs).not.toContain(`[${path}] connection(): ok`)
expect(logs).toContain(
`[${path}] connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\`.`
`[${path}] connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\` while rendering.`
)
})
await retry(() => {
......@@ -73,17 +64,17 @@ describe('nextjs APIs in after()', () => {
expect(logs).not.toContain(`[${path}] nested headers(): ok`)
expect(logs).toContain(
`[${path}] nested headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\`. This is not supported.`
`[${path}] nested headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\` while rendering. This is not supported.`
)
expect(logs).not.toContain(`[${path}] nested cookies(): ok`)
expect(logs).toContain(
`[${path}] nested cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\`. This is not supported.`
`[${path}] nested cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\` while rendering. This is not supported.`
)
expect(logs).not.toContain(`[${path}] nested connection(): ok`)
expect(logs).toContain(
`[${path}] nested connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\`.`
`[${path}] nested connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\` while rendering.`
)
})
})
......@@ -105,17 +96,17 @@ describe('nextjs APIs in after()', () => {
expect(logs).not.toContain(`[${path}] headers(): ok`)
expect(logs).toContain(
`[${path}] headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\`. This is not supported.`
`[${path}] headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\` while rendering. This is not supported.`
)
expect(logs).not.toContain(`[${path}] cookies(): ok`)
expect(logs).toContain(
`[${path}] cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\`. This is not supported.`
`[${path}] cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\` while rendering. This is not supported.`
)
expect(logs).not.toContain(`[${path}] connection(): ok`)
expect(logs).toContain(
`[${path}] connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\`.`
`[${path}] connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\` while rendering.`
)
})
await retry(() => {
......@@ -123,17 +114,17 @@ describe('nextjs APIs in after()', () => {
expect(logs).not.toContain(`[${path}] nested headers(): ok`)
expect(logs).toContain(
`[${path}] nested headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\`. This is not supported.`
`[${path}] nested headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\` while rendering. This is not supported.`
)
expect(logs).not.toContain(`[${path}] nested cookies(): ok`)
expect(logs).toContain(
`[${path}] nested cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\`. This is not supported.`
`[${path}] nested cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\` while rendering. This is not supported.`
)
expect(logs).not.toContain(`[${path}] nested connection(): ok`)
expect(logs).toContain(
`[${path}] nested connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\`.`
`[${path}] nested connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\` while rendering.`
)
})
})
......@@ -280,4 +271,169 @@ describe('nextjs APIs in after()', () => {
})
})
})
describe('async APIs in promises passed to after', () => {
describe('in route handlers', () => {
it.each(REQUEST_API_NAMES)(
'does not error - %s',
async (apiName: string) => {
const cliOutputIndex = next.cliOutput.length
const getCliOutput = () => next.cliOutput.slice(cliOutputIndex)
await next.fetch(
`/request-apis-in-promise/route-handler?api=${apiName}`
)
const cliOutput = await retry(() => {
const cliOutput = getCliOutput()
expect(cliOutput).toContain(`route :: ${apiName} :: finished`)
return cliOutput
})
expect(cliOutput).toContain(`route :: ${apiName} :: promise :: ok`)
expect(cliOutput).not.toContain(
`route :: ${apiName} :: promise :: error`
)
expect(cliOutput).toContain(
`route :: ${apiName} :: nested after :: ok`
)
expect(cliOutput).not.toContain(
`route :: ${apiName} :: nested after :: error`
)
}
)
})
describe('in server actions', () => {
it.each(REQUEST_API_NAMES)(
'does not error - %s',
async (apiName: string) => {
const browser = await next.browser(
`/request-apis-in-promise/server-action`
)
const cliOutputIndex = next.cliOutput.length
const getCliOutput = () => next.cliOutput.slice(cliOutputIndex)
await browser
.elementByCss(
`form[data-api-name="${apiName}"] button[type="submit"]`
)
.click()
const cliOutput = await retry(() => {
const cliOutput = getCliOutput()
expect(cliOutput).toContain(`action :: ${apiName} :: finished`)
return cliOutput
})
expect(cliOutput).toContain(`action :: ${apiName} :: promise :: ok`)
expect(cliOutput).not.toContain(
`action :: ${apiName} :: promise :: error`
)
expect(cliOutput).toContain(
`action :: ${apiName} :: nested after :: ok`
)
expect(cliOutput).not.toContain(
`action :: ${apiName} :: nested after :: error`
)
}
)
})
describe('in renders', () => {
it.each(REQUEST_API_NAMES)(
'throws an error - %s',
async (apiName: string) => {
const route = `/request-apis-in-promise/render`
const path = `${route}?apiName=${apiName}`
const cliOutputIndex = next.cliOutput.length
const getCliOutput = () => next.cliOutput.slice(cliOutputIndex)
await next.fetch(path)
const cliOutput = await retry(() => {
const cliOutput = getCliOutput()
expect(cliOutput).toContain(`render :: ${apiName} :: finished`)
return cliOutput
})
const message = `Error: Route ${route} used \`${apiName}()\` inside \`after()\` while rendering.`
expect(cliOutput).toContain(
`render :: ${apiName} :: promise :: error: ${message}`
)
expect(cliOutput).not.toContain(
`render :: ${apiName} :: promise :: ok`
)
expect(cliOutput).toContain(
`render :: ${apiName} :: nested after :: error: ${message}`
)
expect(cliOutput).not.toContain(
`render :: ${apiName} :: nested after :: ok`
)
}
)
})
describe('in renders after server actions', () => {
it.each(REQUEST_API_NAMES)(
'throws an error - %s',
async (apiName: string) => {
const route = '/request-apis-in-promise/render-after-action'
const initialCliOutputIndex = next.cliOutput.length
const browser = await next.browser(route)
// Clear cookies after every run
await using _ = defer(() => browser.deleteCookies())
// Sanity check: we should not be running any of the APIs now,
// only when a server action causes a rerender
expect(next.cliOutput.slice(initialCliOutputIndex)).not.toContain(
`render after action :: ${apiName} :: starting`
)
const cliOutputIndex = next.cliOutput.length
const getCliOutput = () => next.cliOutput.slice(cliOutputIndex)
await browser
.elementByCss(
`form[data-api-name="${apiName}"] button[type="submit"]`
)
.click()
const cliOutput = await retry(() => {
const cliOutput = getCliOutput()
expect(cliOutput).toContain(
`render after action :: ${apiName} :: finished`
)
return cliOutput
})
const message = `Error: Route ${route} used \`${apiName}()\` inside \`after()\` while rendering.`
expect(cliOutput).toContain(
`render after action :: ${apiName} :: promise :: error: ${message}`
)
expect(cliOutput).not.toContain(
`render after action :: ${apiName} :: promise :: ok`
)
expect(cliOutput).toContain(
`render after action :: ${apiName} :: nested after :: error: ${message}`
)
expect(cliOutput).not.toContain(
`render after action :: ${apiName} :: nested after :: ok`
)
}
)
})
})
})
function defer(callback: () => void | Promise<void>): AsyncDisposable {
return {
[Symbol.asyncDispose]: async () => {
return callback()
},
}
}
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