Unverified Commit f17e61cb authored by Josh Story's avatar Josh Story Committed by GitHub

Keep dynamic asset prefixes outside configuration (#99490)

## Summary

Keep custom-server asset prefix changes in server render state, with
rendering and routing reading the same runtime value. Setting and
resetting the prefix continues to work without modifying or copying the
loaded config. This supports the broader effort to make Next.js
configuration immutable for adapters.

Adds a public custom-server test for App Router asset URLs, including
reset to an empty prefix.

## Verification

- Existing Pages custom-server dynamic-prefix tests pass in production
with Webpack and development with Turbopack (24 cases each).
- The production custom-server suite passes with Webpack; the new App
Router case also passes with Turbopack.

<!-- NEXT_JS_LLM -->
parent 907721a6
......@@ -942,7 +942,10 @@ export function createAppPageEntrypoint({
botType,
isOnDemandRevalidate,
isPossibleServerAction,
assetPrefix: nextConfig.assetPrefix,
assetPrefix: routeModule.getAssetPrefixForRender(
routerServerContext,
nextConfig.assetPrefix
),
nextConfigOutput: nextConfig.output,
crossOrigin: nextConfig.crossOrigin,
trailingSlash: nextConfig.trailingSlash,
......
......@@ -2044,7 +2044,11 @@ export default abstract class Server<
): Promise<void>
public setAssetPrefix(prefix?: string): void {
this.nextConfig.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
}
public getAssetPrefix(): string {
return this.renderOpts.assetPrefix || ''
}
protected prepared: boolean = false
......
......@@ -368,6 +368,7 @@ export async function initialize(opts: {
const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {
addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)
const assetPrefix = getAssetPrefix()
// internal headers should not be honored by the request handler
if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {
......@@ -585,11 +586,8 @@ export async function initialize(opts: {
// so that the development bundler can find the correct file
if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {
req.url = removePathPrefix(origUrl, config.basePath)
} else if (
config.assetPrefix &&
pathHasPrefix(origUrl, config.assetPrefix)
) {
req.url = removePathPrefix(origUrl, config.assetPrefix)
} else if (assetPrefix && pathHasPrefix(origUrl, assetPrefix)) {
req.url = removePathPrefix(origUrl, assetPrefix)
}
const parsedUrl = parseUrlUtil(req.url || '/')
......@@ -631,11 +629,8 @@ export async function initialize(opts: {
if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {
req.url = removePathPrefix(origUrl, config.basePath)
} else if (
config.assetPrefix &&
pathHasPrefix(origUrl, config.assetPrefix)
) {
req.url = removePathPrefix(origUrl, config.assetPrefix)
} else if (assetPrefix && pathHasPrefix(origUrl, assetPrefix)) {
req.url = removePathPrefix(origUrl, assetPrefix)
}
if (resHeaders !== null) {
......@@ -871,10 +866,10 @@ export async function initialize(opts: {
config.basePath
)
}
if (config.assetPrefix) {
if (assetPrefix) {
realRequestPathname = removePathPrefix(
realRequestPathname,
config.assetPrefix
assetPrefix
)
}
if (config.i18n) {
......@@ -1005,6 +1000,7 @@ export async function initialize(opts: {
// pre-initialize workers
const handlers = await renderServer.instance.initialize(renderServerOpts)
const getAssetPrefix = () => handlers.server.getAssetPrefix()
// this must come after initialize of render server since it's
// using initialized methods
......@@ -1015,6 +1011,7 @@ export async function initialize(opts: {
routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {
nextConfig: getNextConfigRuntime(config),
getAssetPrefix,
hostname: handlers.server.hostname,
revalidate: handlers.server.revalidate.bind(handlers.server),
render404: handlers.server.render404.bind(handlers.server),
......@@ -1050,6 +1047,7 @@ export async function initialize(opts: {
const resolveRoutes = getResolveRoutes(
fsChecker,
config,
getAssetPrefix,
opts,
renderServer.instance,
renderServerOpts,
......@@ -1078,7 +1076,8 @@ export async function initialize(opts: {
) {
return
}
const { basePath, assetPrefix } = config
const { basePath } = config
const assetPrefix = getAssetPrefix()
let hmrPrefix = basePath
......
......@@ -53,6 +53,7 @@ export function getResolveRoutes(
ReturnType<typeof import('./filesystem').setupFsCheck>
>,
config: NextConfigRuntime,
getAssetPrefix: () => string,
opts: Parameters<typeof initialize>[0],
renderServer: RenderServer,
renderServerOpts: Parameters<RenderServer['initialize']>[0],
......@@ -134,6 +135,7 @@ export function getResolveRoutes(
parsedUrl: NextUrlWithParsedQuery
matchedOutput?: FsOutput | null
}> {
const assetPrefix = getAssetPrefix()
let finished = false
let resHeaders: Record<string, string | string[]> = {}
let matchedOutput: FsOutput | null = null
......@@ -222,11 +224,8 @@ export function getResolveRoutes(
if (config.basePath && pathHasPrefix(normalizedPath, config.basePath)) {
normalizedPath = removePathPrefix(normalizedPath, config.basePath)
} else if (
config.assetPrefix &&
pathHasPrefix(normalizedPath, config.assetPrefix)
) {
normalizedPath = removePathPrefix(normalizedPath, config.assetPrefix)
} else if (assetPrefix && pathHasPrefix(normalizedPath, assetPrefix)) {
normalizedPath = removePathPrefix(normalizedPath, assetPrefix)
}
initialLocaleResult = normalizeLocalePath(
......
......@@ -10,11 +10,9 @@ export type RevalidateFn = (config: {
opts: { unstable_onlyGenerated?: boolean }
}) => Promise<void>
// The RouterServerContext contains instance specific
// information that isn't available/relevant when
// deployed in serverless environments, the key is
// the relative project dir this allows separate contexts
// when running multiple next instances in same process
// Services and runtime state supplied by a running NextServer, keyed by the
// relative project dir so multiple instances can share a process. Built route
// handlers can also run without a NextServer or this context.
export type RouterServerContext = Record<
string,
{
......@@ -32,6 +30,8 @@ export type RouterServerContext = Record<
) => Promise<void>
// exposing nextConfig for dev mode specifically
nextConfig?: NextConfigRuntime
// Current server-owned prefix; absent when no NextServer owns this route.
getAssetPrefix?: () => string
// whether running in custom server mode
isCustomServer?: boolean
// whether test proxy is enabled
......
......@@ -1169,6 +1169,7 @@ export default class NextNodeServer extends BaseServer<
if (!existingServerContext) {
routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {
render404: this.render404.bind(this),
getAssetPrefix: this.getAssetPrefix.bind(this),
}
}
routerServerGlobal[RouterServerContextSymbol][
......
......@@ -26,10 +26,6 @@ import { formatUrl } from '../shared/lib/router/utils/format-url'
import type { ServerFields } from './lib/router-utils/setup-dev-bundler'
import type { ServerInitResult } from './lib/render-server'
import { AsyncCallbackSet } from './lib/async-callback-set'
import {
RouterServerContextSymbol,
routerServerGlobal,
} from './lib/router-utils/router-server-context'
let ServerImpl: typeof NextNodeServer
......@@ -255,6 +251,13 @@ export class NextServer implements NextWrapperServer {
}
}
getAssetPrefix(): string {
if (!this.server) {
throw new Error('prepare() must be called before getting assetPrefix')
}
return this.server.getAssetPrefix()
}
logError(...args: Parameters<NextWrapperServer['logError']>) {
if (this.server) {
this.server.logError(...args)
......@@ -544,22 +547,6 @@ class NextCustomServer implements NextWrapperServer {
setAssetPrefix(assetPrefix: string): void {
warnDeprecatedCustomServerMethod('setAssetPrefix')
this.server.setAssetPrefix(assetPrefix)
// update the router-server nextConfig instance as
// this is the source of truth for "handler" in serverful
const relativeProjectDir = path.relative(
process.cwd(),
this.options.dir || ''
)
if (
routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]
?.nextConfig
) {
routerServerGlobal[RouterServerContextSymbol][
relativeProjectDir
].nextConfig.assetPrefix = assetPrefix
}
}
getUpgradeHandler(): UpgradeHandler {
......
......@@ -317,7 +317,10 @@ export const getHandler = ({
nextFontManifest,
reactLoadableManifest,
assetPrefix: nextConfig.assetPrefix,
assetPrefix: routeModule.getAssetPrefixForRender(
routerServerContext,
nextConfig.assetPrefix
),
previewProps,
images: nextConfig.images as any,
nextConfigOutput: nextConfig.output,
......
......@@ -182,6 +182,18 @@ export abstract class RouteModule<
}
}
public getAssetPrefixForRender(
routerServerContext: RouterServerContext[string] | undefined,
configuredAssetPrefix: string
): string {
// A running NextServer owns overrides from app.setAssetPrefix().
if (routerServerContext && routerServerContext.getAssetPrefix) {
return routerServerContext.getAssetPrefix()
}
// Direct route invocations use the configured prefix.
return configuredAssetPrefix
}
public normalizeUrl(
_req: IncomingMessage | BaseNextRequest,
_parsedUrl: UrlWithParsedQuery
......
export const dynamic = 'force-dynamic'
export default function Page() {
return <div>asset prefix page</div>
}
......@@ -20,6 +20,24 @@ describe('custom server', () => {
expect(next.cliOutput).toInclude('Server side error')
})
it('updates App Router asset URLs when the custom server changes the prefix', async () => {
const localAssets =
'script[src^="/_next/static/"], link[href^="/_next/static/"]'
const prefixedAssets =
'script[src^="https://cdn.example.com/_next/static/"], link[href^="https://cdn.example.com/_next/static/"]'
const initial = await next.render$('/asset-prefix')
expect(initial(localAssets).length).toBeGreaterThan(0)
expect(initial(prefixedAssets).length).toBe(0)
const updated = await next.render$('/asset-prefix?assetPrefix=set')
expect(updated(prefixedAssets).length).toBeGreaterThan(0)
const reset = await next.render$('/asset-prefix?assetPrefix=reset')
expect(reset(localAssets).length).toBeGreaterThan(0)
expect(reset(prefixedAssets).length).toBe(0)
})
describe('with app dir', () => {
it('should render app with react canary', async () => {
const $ = await next.render$(`/1`)
......
......@@ -34,6 +34,14 @@ async function main() {
pathname = pathname.replace(conf.basePath, '') || '/'
}
if (pathname === '/asset-prefix' && parsedUrl.query.assetPrefix) {
app.setAssetPrefix(
parsedUrl.query.assetPrefix === 'reset'
? ''
: 'https://cdn.example.com'
)
}
parsedUrl.pathname =
pathname === '/b'
? '/page-b'
......
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