Unverified Commit 6d05b837 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Experimental deferred entries handling (#88347)

This is just an exploration into a deferred entries hook in
`next.config` to allow waiting to build specific entries until all other
entries have processed allowing external discovery of assets from
compilation that can be used in building these deferred entries.

x-ref: [slack
thread](https://vercel.slack.com/archives/C09125LC4AX/p1767991281352189?thread_ts=1766951034.768869&cid=C09125LC4AX)
parent b08049cc
......@@ -593,6 +593,47 @@ export interface CreateEntrypointsParams {
appPaths?: MappedPages
pageExtensions: PageExtensions
hasInstrumentationHook?: boolean
/**
* When set to 'exclude', deferred entries are excluded from the result.
* When set to 'only', only deferred entries are included in the result.
* When undefined, all entries are included.
*/
deferredEntriesFilter?: 'exclude' | 'only'
}
/**
* Checks if a page path matches any of the deferred entry patterns.
* @param page - The page path (e.g., '/about', '/api/hello')
* @param deferredEntries - Array of path patterns to match against
* @returns true if the page matches a deferred entry pattern
*/
export function isDeferredEntry(
page: string,
deferredEntries: string[] | undefined
): boolean {
if (!deferredEntries || deferredEntries.length === 0) {
return false
}
// Normalize the page path
const normalizedPage = page.startsWith('/') ? page : `/${page}`
for (const pattern of deferredEntries) {
// Normalize the pattern
const normalizedPattern = pattern.startsWith('/') ? pattern : `/${pattern}`
// Check for exact match or prefix match for directories
if (normalizedPage === normalizedPattern) {
return true
}
// Check if the page is under the deferred directory
if (normalizedPage.startsWith(normalizedPattern + '/')) {
return true
}
}
return false
}
export function getEdgeServerEntry(opts: {
......@@ -838,7 +879,10 @@ export async function createEntrypoints(
appDir,
appPaths,
pageExtensions,
deferredEntriesFilter,
} = params
const deferredEntries = config.experimental.deferredEntries
const edgeServer: webpack.EntryObject = {}
const server: webpack.EntryObject = {}
const client: webpack.EntryObject = {}
......@@ -870,6 +914,19 @@ export async function createEntrypoints(
const getEntryHandler =
(mappings: MappedPages, pagesType: PAGE_TYPES): ((page: string) => void) =>
async (page) => {
// Apply deferred entries filter if specified
if (deferredEntriesFilter) {
const isDeferred = isDeferredEntry(page, deferredEntries)
if (deferredEntriesFilter === 'exclude' && isDeferred) {
// Skip deferred entries when excluding them
return
}
if (deferredEntriesFilter === 'only' && !isDeferred) {
// Skip non-deferred entries when only including deferred ones
return
}
}
const bundleFile = normalizePagePath(page)
const clientBundlePath = posix.join(pagesType, bundleFile)
const serverBundlePath =
......
......@@ -89,6 +89,12 @@ export async function webpackBuildImpl(
process.env.NEXT_COMPILER_NAME = compilerName || 'server'
const runWebpackSpan = nextBuildSpan.traceChild('run-webpack-compiler')
const hasDeferredEntries =
config.experimental.deferredEntries &&
config.experimental.deferredEntries.length > 0
// Create entrypoints - exclude deferred entries if configured
const entrypoints = await nextBuildSpan
.traceChild('create-entrypoints')
.traceAsyncFn(() =>
......@@ -106,9 +112,34 @@ export async function webpackBuildImpl(
previewMode: NextBuildContext.previewProps!,
rootPaths: NextBuildContext.mappedRootPaths!,
hasInstrumentationHook: NextBuildContext.hasInstrumentationHook!,
deferredEntriesFilter: hasDeferredEntries ? 'exclude' : undefined,
})
)
// Create deferred entrypoints if configured
const deferredEntrypoints = hasDeferredEntries
? await nextBuildSpan
.traceChild('create-deferred-entrypoints')
.traceAsyncFn(() =>
createEntrypoints({
buildId: NextBuildContext.buildId!,
config: config,
envFiles: NextBuildContext.loadedEnvFiles!,
isDev: false,
rootDir: dir,
pageExtensions: config.pageExtensions!,
pagesDir: NextBuildContext.pagesDir!,
appDir: NextBuildContext.appDir!,
pages: NextBuildContext.mappedPages!,
appPaths: NextBuildContext.mappedAppPages!,
previewMode: NextBuildContext.previewProps!,
rootPaths: NextBuildContext.mappedRootPaths!,
hasInstrumentationHook: NextBuildContext.hasInstrumentationHook!,
deferredEntriesFilter: 'only',
})
)
: null
const commonWebpackOptions = {
isServer: false,
isCompileMode: NextBuildContext.isCompileMode,
......@@ -143,6 +174,7 @@ export async function webpackBuildImpl(
runWebpackSpan,
compilerType: COMPILER_NAMES.client,
entrypoints: entrypoints.client,
deferredEntrypoints: deferredEntrypoints?.client,
...info,
}),
getBaseWebpackConfig(dir, {
......@@ -151,6 +183,7 @@ export async function webpackBuildImpl(
middlewareMatchers: entrypoints.middlewareMatchers,
compilerType: COMPILER_NAMES.server,
entrypoints: entrypoints.server,
deferredEntrypoints: deferredEntrypoints?.server,
...info,
}),
getBaseWebpackConfig(dir, {
......@@ -159,6 +192,7 @@ export async function webpackBuildImpl(
middlewareMatchers: entrypoints.middlewareMatchers,
compilerType: COMPILER_NAMES.edgeServer,
entrypoints: entrypoints.edgeServer,
deferredEntrypoints: deferredEntrypoints?.edgeServer,
...info,
}),
])
......
......@@ -51,6 +51,7 @@ import { CopyFilePlugin } from './webpack/plugins/copy-file-plugin'
import { ClientReferenceManifestPlugin } from './webpack/plugins/flight-manifest-plugin'
import { FlightClientEntryPlugin as NextFlightClientEntryPlugin } from './webpack/plugins/flight-client-entry-plugin'
import { RspackFlightClientEntryPlugin } from './webpack/plugins/rspack-flight-client-entry-plugin'
import { DeferredEntriesPlugin } from './webpack/plugins/deferred-entries-plugin'
import { NextTypesPlugin } from './webpack/plugins/next-types-plugin'
import type {
Feature,
......@@ -320,6 +321,7 @@ export default async function getBaseWebpackConfig(
compilerType,
dev = false,
entrypoints,
deferredEntrypoints,
isDevFallback = false,
pagesDir,
reactProductionProfiling = false,
......@@ -347,6 +349,7 @@ export default async function getBaseWebpackConfig(
compilerType: CompilerNameValues
dev?: boolean
entrypoints: webpack.EntryObject
deferredEntrypoints?: webpack.EntryObject
isDevFallback?: boolean
pagesDir: string | undefined
reactProductionProfiling?: boolean
......@@ -1972,6 +1975,15 @@ export default async function getBaseWebpackConfig(
//
// TODO: Rspack currently does not support the hooks and chunk methods required by ForceCompleteRuntimePlugin.
dev && !isRspack && new ForceCompleteRuntimePlugin(),
// Handle deferred entries - must be added early to intercept entry processing
!isRspack &&
config.experimental.deferredEntries?.length &&
deferredEntrypoints &&
new DeferredEntriesPlugin({
dev,
config,
deferredEntrypoints,
}),
isNodeServer &&
new bundler.NormalModuleReplacementPlugin(
/\.\/(.+)\.shared-runtime$/,
......
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type { NextConfigComplete } from '../../../server/config-shared'
import createDebug from 'next/dist/compiled/debug'
const debug = createDebug('next:deferred-entries-plugin')
const PLUGIN_NAME = 'DeferredEntriesPlugin'
interface DeferredEntriesPluginOptions {
dev: boolean
config: NextConfigComplete
deferredEntrypoints?: webpack.EntryObject
}
/**
* A webpack plugin that handles deferred entries by:
* 1. Accepting deferred entrypoints separately from the main config
* 2. After non-deferred entries are compiled, calling the onBeforeDeferredEntries callback
* 3. Then adding and compiling the deferred entries within the same compilation
*
* This approach avoids module ID conflicts that would occur with separate compilations.
*/
export class DeferredEntriesPlugin {
private onBeforeDeferredEntries?: () => Promise<void>
private deferredEntrypoints?: webpack.EntryObject
private callbackCalled: boolean = false
constructor(options: DeferredEntriesPluginOptions) {
this.onBeforeDeferredEntries =
options.config.experimental.onBeforeDeferredEntries
this.deferredEntrypoints = options.deferredEntrypoints
}
apply(compiler: webpack.Compiler) {
// Skip if no deferred entrypoints to process
if (
!this.deferredEntrypoints ||
Object.keys(this.deferredEntrypoints).length === 0
) {
return
}
// Use finishMake hook to add deferred entries after all initial entries are processed
// This is the same pattern used by FlightClientEntryPlugin
compiler.hooks.finishMake.tapPromise(PLUGIN_NAME, async (compilation) => {
// Only process if we haven't called callback yet
if (this.callbackCalled) {
return
}
this.callbackCalled = true
// Call the onBeforeDeferredEntries callback
if (this.onBeforeDeferredEntries) {
debug('calling onBeforeDeferredEntries callback')
await this.onBeforeDeferredEntries()
debug('onBeforeDeferredEntries callback completed')
}
// Add deferred entries to compilation
const addEntryPromises: Promise<void>[] = []
const bundler = webpack
debug('adding deferred entries:', Object.keys(this.deferredEntrypoints!))
for (const [name, entryData] of Object.entries(
this.deferredEntrypoints!
)) {
debug('processing deferred entry:', name, entryData)
// Normalize entry data structure
let entry: {
import?: string | string[]
layer?: string
runtime?: string | false
dependOn?: string | string[]
}
if (typeof entryData === 'string') {
entry = { import: [entryData] }
} else if (Array.isArray(entryData)) {
entry = { import: entryData }
} else {
entry = entryData as typeof entry
}
// Get imports array
const imports = entry.import
? Array.isArray(entry.import)
? entry.import
: [entry.import]
: []
if (imports.length === 0) {
continue
}
// Normalize dependOn to always be an array
const dependOn = entry.dependOn
? Array.isArray(entry.dependOn)
? entry.dependOn
: [entry.dependOn]
: undefined
// Create dependencies for all imports
for (const importPath of imports) {
if (typeof importPath !== 'string') {
continue
}
const dep = bundler.EntryPlugin.createDependency(importPath, {
name,
})
addEntryPromises.push(
new Promise((resolve, reject) => {
compilation.addEntry(
compiler.context,
dep,
{
name,
layer: entry.layer,
runtime: entry.runtime,
dependOn,
},
(err) => {
if (err) {
reject(err)
} else {
resolve()
}
}
)
})
)
}
}
await Promise.all(addEntryPromises)
})
}
}
......@@ -370,6 +370,8 @@ export const experimentalSchema = {
hideLogsAfterAbort: z.boolean().optional(),
runtimeServerDeploymentId: z.boolean().optional(),
devCacheControlNoCache: z.boolean().optional(),
deferredEntries: z.array(z.string()).optional(),
onBeforeDeferredEntries: z.function().returns(z.promise(z.void())).optional(),
}
export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
......
......@@ -925,6 +925,19 @@ export interface ExperimentalConfig {
* @default false
*/
devCacheControlNoCache?: boolean
/**
* An array of paths in app or pages directories that should wait to be processed
* until all other entries have been processed. This is useful for deferring
* compilation of certain routes during development and build.
*/
deferredEntries?: string[]
/**
* An async function that is called and awaited before processing deferred entries.
* This callback runs after all non-deferred entries have been compiled.
*/
onBeforeDeferredEntries?: () => Promise<void>
}
export type ExportPathMap = {
......
......@@ -79,6 +79,7 @@ import { generateEncryptionKeyBase64 } from '../app-render/encryption-utils-serv
import { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import type { ModernSourceMapPayload } from '../lib/source-maps'
import { isDeferredEntry } from '../../build/entries'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'
import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'
......@@ -338,6 +339,73 @@ export async function createHotReloaderTurbopack(
const assetMapper = new AssetMapper()
// Deferred entries state management
const deferredEntriesConfig = nextConfig.experimental.deferredEntries
const hasDeferredEntriesConfig =
deferredEntriesConfig && deferredEntriesConfig.length > 0
let onBeforeDeferredEntriesCalled = false
let onBeforeDeferredEntriesPromise: Promise<void> | null = null
// Track non-deferred entries that are currently being built
const nonDeferredBuildingEntries: Set<string> = new Set()
// Function to wait for all non-deferred entries to be built
async function waitForNonDeferredEntries(): Promise<void> {
return new Promise<void>((resolve) => {
const checkEntries = () => {
// Check if there are any non-deferred entries that are still building
if (nonDeferredBuildingEntries.size === 0) {
resolve()
} else {
// Check again after a short delay
setTimeout(checkEntries, 100)
}
}
checkEntries()
})
}
// Function to handle deferred entry processing
async function processDeferredEntry(): Promise<void> {
if (!hasDeferredEntriesConfig) return
// Wait for all non-deferred entries to be built
await waitForNonDeferredEntries()
// Call the onBeforeDeferredEntries callback once
if (!onBeforeDeferredEntriesCalled) {
onBeforeDeferredEntriesCalled = true
if (nextConfig.experimental.onBeforeDeferredEntries) {
if (!onBeforeDeferredEntriesPromise) {
onBeforeDeferredEntriesPromise =
nextConfig.experimental.onBeforeDeferredEntries()
}
await onBeforeDeferredEntriesPromise
}
} else if (onBeforeDeferredEntriesPromise) {
// Wait for any in-progress callback
await onBeforeDeferredEntriesPromise
}
}
// Track whether HMR is pending - used to call callback once after HMR settles
let hmrPendingDeferredCallback = false
// Debounced function to call onBeforeDeferredEntries after HMR
// This prevents rapid-fire calls when turbopack fires many update events
// Use 500ms debounce to ensure all rapid updates are batched together
const callOnBeforeDeferredEntriesAfterHMR = debounce(() => {
// Only call if HMR triggered a need for the callback
if (hasDeferredEntriesConfig && hmrPendingDeferredCallback) {
hmrPendingDeferredCallback = false
onBeforeDeferredEntriesCalled = true
if (nextConfig.experimental.onBeforeDeferredEntries) {
onBeforeDeferredEntriesPromise =
nextConfig.experimental.onBeforeDeferredEntries()
}
}
}, 500)
function clearRequireCache(
key: EntryKey,
writtenEndpoint: WrittenEndpoint,
......@@ -1336,6 +1404,20 @@ export async function createHotReloaderTurbopack(
appPaths = definition.appPaths
}
// Check if this is a deferred entry and wait for non-deferred entries first
if (hasDeferredEntriesConfig) {
const isDeferred = isDeferredEntry(
routeDef.page,
deferredEntriesConfig
)
if (isDeferred) {
await processDeferredEntry()
} else {
// Track non-deferred entry as building
nonDeferredBuildingEntries.add(routeDef.page)
}
}
let page = routeDef.page
if (appPaths) {
const normalizedPage = normalizeAppPath(page)
......@@ -1442,6 +1524,10 @@ export async function createHotReloaderTurbopack(
})
} finally {
finishBuilding()
// Remove non-deferred entry from building set
if (hasDeferredEntriesConfig) {
nonDeferredBuildingEntries.delete(routeDef.page)
}
}
})
},
......@@ -1479,6 +1565,13 @@ export async function createHotReloaderTurbopack(
switch (updateMessage.updateType) {
case 'start': {
hotReloader.send({ type: HMR_MESSAGE_SENT_TO_BROWSER.BUILDING })
// Mark that HMR has started and we need to call the callback after it settles
// This ensures onBeforeDeferredEntries will be called again during HMR
if (hasDeferredEntriesConfig) {
hmrPendingDeferredCallback = true
onBeforeDeferredEntriesCalled = false
onBeforeDeferredEntriesPromise = null
}
break
}
case 'end': {
......@@ -1543,6 +1636,13 @@ export async function createHotReloaderTurbopack(
Log.event(`Compiled in ${timeMessage}`)
hmrEventHappened = false
}
// Call onBeforeDeferredEntries after compilation completes during HMR
// This ensures the callback is invoked even when non-deferred entries change
// Use debounced function to prevent rapid-fire calls from turbopack updates
if (hasDeferredEntriesConfig) {
callOnBeforeDeferredEntriesAfterHMR()
}
break
}
default:
......
......@@ -12,7 +12,7 @@ import type { RouteDefinition } from '../route-definitions/route-definition'
import createDebug from 'next/dist/compiled/debug'
import { EventEmitter } from 'events'
import { findPageFile } from '../lib/find-page-file'
import { runDependingOnPageType } from '../../build/entries'
import { runDependingOnPageType, isDeferredEntry } from '../../build/entries'
import { getStaticInfoIncludingLayouts } from '../../build/get-static-info-including-layouts'
import { join, posix } from 'path'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
......@@ -568,9 +568,83 @@ export function onDemandEntryHandler({
invalidators.set(multiCompiler.outputPath, curInvalidator)
}
// Deferred entries state management
const deferredEntriesConfig = nextConfig.experimental.deferredEntries
const hasDeferredEntriesConfig =
deferredEntriesConfig && deferredEntriesConfig.length > 0
let onBeforeDeferredEntriesCalled = false
let onBeforeDeferredEntriesPromise: Promise<void> | null = null
// Function to wait for all non-deferred entries to be built
async function waitForNonDeferredEntries(): Promise<void> {
return new Promise<void>((resolve) => {
const checkEntries = () => {
// Check if there are any non-deferred entries that are still building or added
const hasNonDeferredEntriesBuilding = Object.entries(curEntries).some(
([, entry]) => {
const entryData = entry as Entry | ChildEntry
if (entryData.type !== EntryTypes.ENTRY) return false
const isDeferred = isDeferredEntry(
(entryData as Entry).absolutePagePath
.replace(appDir || '', '')
.replace(pagesDir || '', '')
.replace(rootDir, ''),
deferredEntriesConfig
)
return (
!isDeferred &&
(entryData.status === ADDED || entryData.status === BUILDING)
)
}
)
if (!hasNonDeferredEntriesBuilding) {
resolve()
} else {
// Check again after a short delay
setTimeout(checkEntries, 100)
}
}
checkEntries()
})
}
// Function to handle deferred entry processing
async function processDeferredEntry(): Promise<void> {
if (!hasDeferredEntriesConfig) return
// Wait for all non-deferred entries to be built
await waitForNonDeferredEntries()
// Call the onBeforeDeferredEntries callback once
if (!onBeforeDeferredEntriesCalled) {
onBeforeDeferredEntriesCalled = true
if (nextConfig.experimental.onBeforeDeferredEntries) {
debug('calling onBeforeDeferredEntries callback')
if (!onBeforeDeferredEntriesPromise) {
onBeforeDeferredEntriesPromise =
nextConfig.experimental.onBeforeDeferredEntries()
}
await onBeforeDeferredEntriesPromise
debug('onBeforeDeferredEntries callback completed')
}
} else if (onBeforeDeferredEntriesPromise) {
// Wait for any in-progress callback
await onBeforeDeferredEntriesPromise
}
}
const startBuilding = (compilation: webpack.Compilation) => {
const compilationName = compilation.name as any as CompilerNameValues
curInvalidator.startBuilding(compilationName)
// Reset deferred entries state for this compilation cycle
// This ensures onBeforeDeferredEntries will be called again during HMR
onBeforeDeferredEntriesCalled = false
onBeforeDeferredEntriesPromise = null
}
for (const compiler of multiCompiler.compilers) {
compiler.hooks.make.tap('NextJsOnDemandEntries', startBuilding)
......@@ -643,6 +717,17 @@ export function onDemandEntryHandler({
}
getInvalidator(multiCompiler.outputPath)?.doneBuilding([...COMPILER_KEYS])
// Call onBeforeDeferredEntries after compilation completes during HMR
// This ensures the callback is invoked even when non-deferred entries change
if (hasDeferredEntriesConfig && !onBeforeDeferredEntriesCalled) {
onBeforeDeferredEntriesCalled = true
if (nextConfig.experimental.onBeforeDeferredEntries) {
debug('calling onBeforeDeferredEntries callback after HMR')
onBeforeDeferredEntriesPromise =
nextConfig.experimental.onBeforeDeferredEntries()
}
}
})
const pingIntervalTime = Math.max(1000, Math.min(5000, maxInactiveAge))
......@@ -762,6 +847,16 @@ export function onDemandEntryHandler({
const isInsideAppDir = !!appDir && route.filename.startsWith(appDir)
// Check if this is a deferred entry and wait for non-deferred entries first
if (hasDeferredEntriesConfig) {
const isDeferred = isDeferredEntry(route.page, deferredEntriesConfig)
if (isDeferred) {
debug(`Page ${page} is a deferred entry, waiting for other entries`)
await processDeferredEntry()
debug(`Deferred entry ${page} can now be processed`)
}
}
if (typeof isApp === 'boolean' && isApp !== isInsideAppDir) {
Error.stackTraceLimit = 15
throw new Error(
......
export default function DeferredPage() {
return <h1>Deferred Page</h1>
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Home() {
return <h1>Home Page</h1>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import fs from 'fs'
import path from 'path'
interface LogEntry {
timestamp: number
entry: string
}
function parseEntryLog(logPath: string): LogEntry[] {
if (!fs.existsSync(logPath)) {
return []
}
const content = fs.readFileSync(logPath, 'utf-8')
return content
.split('\n')
.filter(Boolean)
.map((line) => {
const [timestamp, ...rest] = line.split(':')
return { timestamp: parseInt(timestamp, 10), entry: rest.join(':') }
})
}
function parseCallbackLog(logPath: string): number | null {
if (!fs.existsSync(logPath)) {
return null
}
const content = fs.readFileSync(logPath, 'utf-8')
const lines = content.split('\n').filter(Boolean)
if (lines.length === 0) {
return null
}
const [, timestamp] = lines[0].split(':')
return parseInt(timestamp, 10)
}
describe('deferred-entries webpack', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
dependencies: {},
})
if (skipped) return
beforeAll(async () => {
// Clear log files before starting
const entryLogPath = path.join(next.testDir, '.entry-log')
const callbackLogPath = path.join(next.testDir, '.callback-log')
try {
fs.writeFileSync(entryLogPath, '')
fs.writeFileSync(callbackLogPath, '')
} catch (e) {
// Ignore
}
await next.start()
})
afterAll(async () => {
await next.stop()
})
it('should build deferred entry successfully', async () => {
// Access the deferred page - use retry to handle on-demand compilation timing
await retry(async () => {
const deferredRes = await next.fetch('/deferred')
expect(deferredRes.status).toBe(200)
expect(await deferredRes.text()).toContain('Deferred Page')
})
})
it('should build pages router routes when using deferred entries', async () => {
// Verify pages router page works alongside deferred app router entries
await retry(async () => {
const legacyRes = await next.fetch('/legacy')
expect(legacyRes.status).toBe(200)
expect(await legacyRes.text()).toContain('Legacy Pages Router Page')
})
})
it('should build pages router API routes when using deferred entries', async () => {
// Verify pages router API route works alongside deferred app router entries
await retry(async () => {
const apiRes = await next.fetch('/api/hello')
expect(apiRes.status).toBe(200)
const data = await apiRes.json()
expect(data.message).toBe('Hello from pages API route')
})
})
it('should call onBeforeDeferredEntries before building deferred entry', async () => {
// Verify the callback was executed
const callbackLogPath = path.join(next.testDir, '.callback-log')
await retry(async () => {
const callbackTimestamp = parseCallbackLog(callbackLogPath)
expect(callbackTimestamp).not.toBeNull()
})
})
if (!isNextStart) {
it('should call onBeforeDeferredEntries during HMR even when non-deferred entry changes', async () => {
const callbackLogPath = path.join(next.testDir, '.callback-log')
// First, access the deferred page to trigger the initial callback
await retry(async () => {
const deferredRes = await next.fetch('/deferred')
expect(deferredRes.status).toBe(200)
})
// Access the home page so it gets added to tracked entries for HMR
await retry(async () => {
const homeRes = await next.fetch('/')
expect(homeRes.status).toBe(200)
})
// Get the initial callback timestamp (should now be set)
let initialTimestamp: number | null = null
await retry(async () => {
initialTimestamp = parseCallbackLog(callbackLogPath)
expect(initialTimestamp).not.toBeNull()
})
// Wait a bit to ensure timestamps will be different
await new Promise((resolve) => setTimeout(resolve, 100))
// Modify the home page (non-deferred entry) to trigger HMR
await next.patchFile('app/page.tsx', (content) =>
content.replace('Home Page', 'Home Page Updated')
)
// Wait for HMR to complete and callback to be called again
await retry(async () => {
const newTimestamp = parseCallbackLog(callbackLogPath)
expect(newTimestamp).not.toBeNull()
// The callback should have been called again with a newer timestamp
expect(newTimestamp).toBeGreaterThan(initialTimestamp!)
})
// Verify the home page was updated
await retry(async () => {
const homeRes = await next.fetch('/')
expect(homeRes.status).toBe(200)
expect(await homeRes.text()).toContain('Home Page Updated')
})
})
}
if (isNextStart) {
it('should call onBeforeDeferredEntries before processing deferred entries during build', async () => {
const entryLogPath = path.join(next.testDir, '.entry-log')
const callbackLogPath = path.join(next.testDir, '.callback-log')
// Parse the logs
const entryLog = parseEntryLog(entryLogPath)
const callbackTimestamp = parseCallbackLog(callbackLogPath)
// Debug output
console.log('Entry log:', entryLog)
console.log('Callback timestamp:', callbackTimestamp)
// Verify the callback was executed
expect(callbackTimestamp).not.toBeNull()
// Find the CALLBACK_EXECUTED marker in the entry log
// The callback runs in finishMake hook before the build phase starts
const callbackIndex = entryLog.findIndex(
(e) => e.entry === 'CALLBACK_EXECUTED'
)
expect(callbackIndex).toBeGreaterThan(-1)
// The loader runs during the build phase (after finishMake completes)
// So CALLBACK_EXECUTED should appear before loader entries
// Find loader entries (entries that are file paths, not CALLBACK_EXECUTED)
const loaderEntries = entryLog.filter(
(e) => e.entry !== 'CALLBACK_EXECUTED'
)
// Verify we have loader entries for both home page and deferred page
const homePageEntries = loaderEntries.filter(
(e) => e.entry.includes('page.tsx') && !e.entry.includes('deferred')
)
const deferredPageEntries = loaderEntries.filter((e) =>
e.entry.includes('deferred')
)
console.log('Home page entries:', homePageEntries)
console.log('Deferred page entries:', deferredPageEntries)
expect(homePageEntries.length).toBeGreaterThan(0)
expect(deferredPageEntries.length).toBeGreaterThan(0)
// Verify the callback is called AFTER non-deferred entries
// (non-deferred entries are built first)
const latestNonDeferredTimestamp = Math.max(
...homePageEntries.map((e) => e.timestamp)
)
expect(callbackTimestamp).toBeGreaterThanOrEqual(
latestNonDeferredTimestamp
)
// Verify the callback is called BEFORE deferred entries
// (deferred entries wait for the callback)
const earliestDeferredTimestamp = Math.min(
...deferredPageEntries.map((e) => e.timestamp)
)
expect(callbackTimestamp).toBeLessThanOrEqual(earliestDeferredTimestamp)
// Verify the home page works
const homeRes = await next.fetch('/')
expect(homeRes.status).toBe(200)
expect(await homeRes.text()).toContain('Home Page')
// Verify the deferred page works
const deferredRes = await next.fetch('/deferred')
expect(deferredRes.status).toBe(200)
expect(await deferredRes.text()).toContain('Deferred Page')
})
}
})
const fs = require('fs')
const path = require('path')
// A simple webpack loader that logs when an entry is being processed
module.exports = function entryLoggerLoader(source) {
const callback = this.async()
const resourcePath = this.resourcePath
const logFile = path.join(__dirname, '.entry-log')
console.log('loader', resourcePath)
// Extract the page name from the resource path
let pageName = resourcePath
if (resourcePath.includes('/app/')) {
pageName = resourcePath.split('/app/')[1] || resourcePath
} else if (resourcePath.includes('/pages/')) {
pageName = resourcePath.split('/pages/')[1] || resourcePath
}
// Log the entry processing with timestamp
const logEntry = `${Date.now()}:${pageName}\n`
fs.appendFile(logFile, logEntry, (err) => {
if (err) {
console.error('Failed to write entry log:', err)
}
callback(null, source)
})
}
const fs = require('fs')
const path = require('path')
const logFile = path.join(__dirname, '.entry-log')
const callbackLogFile = path.join(__dirname, '.callback-log')
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
deferredEntries: ['/deferred'],
onBeforeDeferredEntries: async () => {
const timestamp = Date.now()
// Write the callback log file - this file existing proves callback was called
fs.writeFileSync(callbackLogFile, `callback:${timestamp}\n`)
console.log(
`[TEST] onBeforeDeferredEntries callback executed at ${timestamp}`
)
// Small delay to ensure we can verify timing
await new Promise((resolve) => setTimeout(resolve, 100))
// Append to entry log to mark callback position in the build sequence
fs.appendFileSync(logFile, `${timestamp}:CALLBACK_EXECUTED\n`)
},
},
// Turbopack loader configuration
turbopack: {
rules: {
'*.tsx': {
loaders: [
{
loader: path.join(__dirname, 'entry-logger-loader.js'),
},
],
},
},
},
// Webpack loader configuration
webpack: (config, { isServer }) => {
// Add the entry logger loader to track when entries are processed
config.module.rules.push({
test: /\.(tsx|ts|js|jsx)$/,
include: [path.join(__dirname, 'app'), path.join(__dirname, 'pages')],
use: [
{
loader: path.join(__dirname, 'entry-logger-loader.js'),
},
],
})
return config
},
}
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({ message: 'Hello from pages API route' })
}
export default function LegacyPage() {
return (
<div>
<h1>Legacy Pages Router Page</h1>
<p>
This page uses the pages router and should be built alongside app router
pages.
</p>
</div>
)
}
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