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