Unverified Commit 2112cebf authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

For route handlers, call `loadComponents` also during `next build` (#71202)

During `next dev` for route handlers, `loadComponents` is called to load
the route module. This also has the (for now still expected) side-effect
that the reference manifests singleton is set, which we need, to make
`'use cache'` work in route handlers. Until now, `loadComponents` was
not called during `next build` for route handlers, and the module was
loaded separately with `RouteModuleLoader.load`.

With this PR, we are aligning both modes, so that it's always ensured
that the reference manifests singleton is set.

The end goal is to avoid the global singleton completely, but it's still
unclear how to achive this because of the requirements and constrains
that are documented in #62437.
parent 1b871290
......@@ -3,7 +3,6 @@ import type AppRouteRouteModule from '../../server/route-modules/app-route/modul
import type { AppRouteRouteHandlerContext } from '../../server/route-modules/app-route/module'
import type { IncrementalCache } from '../../server/lib/incremental-cache'
import { join } from 'path'
import {
INFINITE_CACHE,
NEXT_BODY_SUFFIX,
......@@ -11,7 +10,6 @@ import {
NEXT_META_SUFFIX,
} from '../../lib/constants'
import { NodeNextRequest } from '../../server/base-http/node'
import { RouteModuleLoader } from '../../server/lib/module-loader/route-module-loader'
import {
NextRequestAdapter,
signalFromNodeResponse,
......@@ -22,7 +20,6 @@ import type {
MockedResponse,
} from '../../server/lib/mock-request'
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { SERVER_DIRECTORY } from '../../shared/lib/constants'
import { hasNextSupport } from '../../server/ci-info'
import { isStaticGenEnabled } from '../../server/route-modules/app-route/helpers/is-static-gen-enabled'
import type { ExperimentalConfig } from '../../server/config-shared'
......@@ -40,8 +37,8 @@ export async function exportAppRoute(
res: MockedResponse,
params: Params | undefined,
page: string,
module: AppRouteRouteModule,
incrementalCache: IncrementalCache | undefined,
distDir: string,
htmlFilepath: string,
fileWriter: FileWriter,
experimental: Required<Pick<ExperimentalConfig, 'after' | 'dynamicIO'>>,
......@@ -86,13 +83,7 @@ export async function exportAppRoute(
context.renderOpts.isRevalidate = true
}
// This is a route handler, which means it has it's handler in the
// bundled file already, we should just use that.
const filename = join(distDir, SERVER_DIRECTORY, 'app', page)
try {
// Route module loading and handling.
const module = await RouteModuleLoader.load<AppRouteRouteModule>(filename)
const userland = module.userland
// we don't bail from the static optimization for
// metadata routes
......
......@@ -47,6 +47,7 @@ import {
} from '../server/request/fallback-params'
import { needsExperimentalReact } from '../lib/needs-experimental-react'
import { runWithCacheScope } from '../server/async-storage/cache-scope'
import type { AppRouteRouteModule } from '../server/route-modules/app-route/module.compiled'
const envConfig = require('../shared/lib/runtime-config.external')
......@@ -235,6 +236,12 @@ async function exportPageImpl(
await fs.mkdir(baseDir, { recursive: true })
const components = await loadComponents({
distDir,
page,
isAppPath: isAppDir,
})
// Handle App Routes.
if (isAppDir && isAppRouteRoute(page)) {
return await exportAppRoute(
......@@ -242,8 +249,8 @@ async function exportPageImpl(
res,
params,
page,
components.routeModule as AppRouteRouteModule,
input.renderOpts.incrementalCache,
distDir,
htmlFilepath,
fileWriter,
input.renderOpts.experimental,
......@@ -251,12 +258,6 @@ async function exportPageImpl(
)
}
const components = await loadComponents({
distDir,
page,
isAppPath: isAppDir,
})
const renderOpts: WorkerRenderOpts = {
...components,
...input.renderOpts,
......
async function getCachedRandom() {
'use cache'
return Math.random()
}
export async function GET() {
const rand1 = await getCachedRandom()
// TODO: Remove this extra micro task when bug in use cache wrapper is fixed.
await Promise.resolve()
const rand2 = await getCachedRandom()
const response = JSON.stringify({ rand1, rand2 })
return new Response(response, {
headers: { 'content-type': 'application/json' },
})
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
dynamicIO: true,
},
}
module.exports = nextConfig
/* eslint-disable jest/no-standalone-expect */
import { nextTestSetup } from 'e2e-utils'
// Explicitly don't mix route handlers with pages in this test app, to make sure
// that this also works in isolation.
describe('use-cache-route-handler-only', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
const itSkipTurbopack = isTurbopack ? it.skip : it
itSkipTurbopack('should cache results in route handlers', async () => {
const response = await next.fetch('/')
const { rand1, rand2 } = await response.json()
expect(rand1).toEqual(rand2)
})
})
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