Commit 0eabab80 authored by Will Binns-Smith's avatar Will Binns-Smith

Fix stale userland config in AppRouteRouteModule after server HMR

With server HMR enabled, AppRouteRouteModule was already re-fetching
the live userland module for the actual handler function via
_getUserland(), but three routing-critical properties (fetchCache,
dynamic, and hasNonStaticMethods) were still read from this.userland —
the static module snapshot captured at cold-boot that is never refreshed
by HMR.

This meant that adding or removing exports like `dynamic = 'force-static'`
or introducing POST/PUT/DELETE handlers required a full server restart
to take effect, even though the handler function body itself updated
correctly.

Fix: resolve the live userland once per request via _getUserland() and
use that single resolved module for all reads in handle(), including
the handler function resolution. Remove the now-redundant
resolveWithGetter() helper.
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 5f258858
...@@ -313,21 +313,6 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -313,21 +313,6 @@ export class AppRouteRouteModule extends RouteModule<
return autoImplementMethods(this.userland as AppRouteUserlandModule)[method] return autoImplementMethods(this.userland as AppRouteUserlandModule)[method]
} }
/**
* Like resolve(), but re-fetches the userland module on every call via the
* async getter. Only used in Turbopack dev mode, where server HMR disposes
* modules between requests. The async wrapper also unwraps async-module
* Promises produced by ESM-only serverExternalPackages.
*/
private async resolveWithGetter(
method: string,
getUserland: () => Promise<AppRouteUserlandModule>
): Promise<AppRouteHandlerFn> {
if (!isHTTPMethod(method)) return () => new Response(null, { status: 400 })
const userland = await getUserland()
return autoImplementMethods(userland)[method]
}
private async do( private async do(
handler: AppRouteHandlerFn, handler: AppRouteHandlerFn,
actionStore: ActionStore, actionStore: ActionStore,
...@@ -720,12 +705,19 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -720,12 +705,19 @@ export class AppRouteRouteModule extends RouteModule<
req: NextRequest, req: NextRequest,
context: AppRouteRouteHandlerContext context: AppRouteRouteHandlerContext
): Promise<Response> { ): Promise<Response> {
// Get the handler function for the given method. In Turbopack dev mode, // In Turbopack dev mode, _getUserland re-fetches the live module from
// use resolveWithGetter() to re-fetch the live userland on every request // devModuleCache on every request so that server HMR updates are picked up
// In all other modes, resolve() is synchronous. // without restarting the process. In all other modes, fall back to the
const handler = this._getUserland // static snapshot captured at construction time.
? await this.resolveWithGetter(req.method, this._getUserland) const liveUserland: AppRouteUserlandModule = this._getUserland
: this.resolve(req.method) ? await this._getUserland()
: this.userland
// Get the handler function for the given method using the live userland.
// Guard against invalid HTTP methods to prevent RCE.
const handler = isHTTPMethod(req.method)
? autoImplementMethods(liveUserland)[req.method]
: () => new Response(null, { status: 400 })
// Get the context for the static generation. // Get the context for the static generation.
const staticGenerationContext: WorkStoreContext = { const staticGenerationContext: WorkStoreContext = {
...@@ -736,7 +728,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -736,7 +728,7 @@ export class AppRouteRouteModule extends RouteModule<
} }
// Add the fetchCache option to the renderOpts. // Add the fetchCache option to the renderOpts.
staticGenerationContext.renderOpts.fetchCache = this.userland.fetchCache staticGenerationContext.renderOpts.fetchCache = liveUserland.fetchCache
const actionStore: ActionStore = { const actionStore: ActionStore = {
isAppRoute: true, isAppRoute: true,
...@@ -770,7 +762,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -770,7 +762,7 @@ export class AppRouteRouteModule extends RouteModule<
this.workAsyncStorage.run(workStore, async () => { this.workAsyncStorage.run(workStore, async () => {
// Check to see if we should bail out of static generation based on // Check to see if we should bail out of static generation based on
// having non-static methods. // having non-static methods.
if (hasNonStaticMethods(this.userland)) { if (hasNonStaticMethods(liveUserland)) {
if (workStore.isStaticGeneration) { if (workStore.isStaticGeneration) {
const err = new DynamicServerError( const err = new DynamicServerError(
'Route is configured with methods that cannot be statically generated.' 'Route is configured with methods that cannot be statically generated.'
...@@ -786,7 +778,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -786,7 +778,7 @@ export class AppRouteRouteModule extends RouteModule<
let request = req let request = req
// Update the static generation store based on the dynamic property. // Update the static generation store based on the dynamic property.
const { dynamic } = this.userland const { dynamic } = liveUserland
switch (dynamic) { switch (dynamic) {
case 'force-dynamic': { case 'force-dynamic': {
// Routes of generated paths should be dynamic // Routes of generated paths should be dynamic
......
import type { NextRequest } from 'next/server'
export const dynamic = 'force-static'
export async function GET(req: NextRequest) {
return Response.json({ search: req.nextUrl.search })
}
...@@ -178,6 +178,32 @@ describe('server-hmr', () => { ...@@ -178,6 +178,32 @@ describe('server-hmr', () => {
}) })
}) })
itTurbopackDev(
'reflects route handler dynamic config changes after HMR',
async () => {
// With dynamic = 'force-static', search params are stripped from the
// request before the handler runs.
const initial = await next
.fetch('/api/dynamic-config?foo=bar')
.then((res) => res.json())
expect(initial.search).toBe('')
// Remove dynamic = 'force-static' to switch to auto mode.
await next.patchFile('app/api/dynamic-config/route.ts', (content) =>
content.replace("export const dynamic = 'force-static'\n\n", '')
)
// After HMR, the live userland should have no dynamic export, so the
// handler receives the real request with search params preserved.
await retry(async () => {
const updated = await next
.fetch('/api/dynamic-config?foo=bar')
.then((res) => res.json())
expect(updated.search).toBe('?foo=bar')
})
}
)
itTurbopackDev( itTurbopackDev(
'does not re-evaluate an unmodified dependency when route changes', 'does not re-evaluate an unmodified dependency when route changes',
async () => { async () => {
......
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