Commit 46f4b309 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig

Don't load build id if missing

parent e0e23b69
...@@ -124,6 +124,7 @@ export async function handler( ...@@ -124,6 +124,7 @@ export async function handler(
const { const {
buildId, buildId,
deploymentId,
params, params,
nextConfig, nextConfig,
parsedUrl, parsedUrl,
...@@ -249,6 +250,7 @@ export async function handler( ...@@ -249,6 +250,7 @@ export async function handler(
}, },
sharedContext: { sharedContext: {
buildId, buildId,
deploymentId,
}, },
} }
const nodeNextReq = new NodeNextRequest(req) const nodeNextReq = new NodeNextRequest(req)
......
...@@ -37,7 +37,7 @@ export type GoodPageCache = { ...@@ -37,7 +37,7 @@ export type GoodPageCache = {
} }
export default class PageLoader { export default class PageLoader {
private buildId: string private buildId: string | undefined
private assetPrefix: string private assetPrefix: string
private promisedSsgManifest: Promise<Set<string>> private promisedSsgManifest: Promise<Set<string>>
private promisedDevPagesManifest?: Promise<string[]> private promisedDevPagesManifest?: Promise<string[]>
...@@ -45,7 +45,7 @@ export default class PageLoader { ...@@ -45,7 +45,7 @@ export default class PageLoader {
public routeLoader: RouteLoader public routeLoader: RouteLoader
constructor(buildId: string, assetPrefix: string) { constructor(buildId: string | undefined, assetPrefix: string) {
this.routeLoader = createRouteLoader(assetPrefix) this.routeLoader = createRouteLoader(assetPrefix)
this.buildId = buildId this.buildId = buildId
......
...@@ -49,7 +49,8 @@ export async function exportAppRoute( ...@@ -49,7 +49,8 @@ export async function exportAppRoute(
fileWriter: MultiFileWriter, fileWriter: MultiFileWriter,
cacheComponents: boolean, cacheComponents: boolean,
experimental: Required<Pick<ExperimentalConfig, 'authInterrupts'>>, experimental: Required<Pick<ExperimentalConfig, 'authInterrupts'>>,
buildId: string buildId: string,
deploymentId: string
): Promise<ExportRouteResult> { ): Promise<ExportRouteResult> {
// Ensure that the URL is absolute. // Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}` req.url = `http://localhost:3000${req.url}`
...@@ -90,6 +91,7 @@ export async function exportAppRoute( ...@@ -90,6 +91,7 @@ export async function exportAppRoute(
}, },
sharedContext: { sharedContext: {
buildId, buildId,
deploymentId,
}, },
} }
......
...@@ -248,7 +248,8 @@ async function exportPageImpl( ...@@ -248,7 +248,8 @@ async function exportPageImpl(
fileWriter, fileWriter,
commonRenderOpts.cacheComponents, commonRenderOpts.cacheComponents,
commonRenderOpts.experimental, commonRenderOpts.experimental,
buildId buildId,
deploymentId
) )
} }
......
...@@ -238,7 +238,7 @@ export type DynamicParam = { ...@@ -238,7 +238,7 @@ export type DynamicParam = {
export type GenerateFlight = typeof generateDynamicFlightRenderResult export type GenerateFlight = typeof generateDynamicFlightRenderResult
export type AppSharedContext = { export type AppSharedContext = {
buildId: string buildId: string | undefined
deploymentId: string deploymentId: string
} }
...@@ -2432,7 +2432,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -2432,7 +2432,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
renderOpts, renderOpts,
// @TODO move to workUnitStore of type Request // @TODO move to workUnitStore of type Request
isPrefetchRequest, isPrefetchRequest,
buildId: sharedContext.buildId, buildId: sharedContext.deploymentId,
previouslyRevalidatedTags, previouslyRevalidatedTags,
nonce, nonce,
}) })
......
...@@ -95,7 +95,8 @@ export interface WorkStore { ...@@ -95,7 +95,8 @@ export interface WorkStore {
isPrefetchRequest?: boolean isPrefetchRequest?: boolean
/** /**
* Prefer `sharedContext.buildId` instead. This only exists because it's needed in use-cache-wrapper * Prefer `sharedContext.buildId` instead. This can also be the deploymentId when available. This
* only exists because it's needed in use-cache-wrapper for cache busting between builds.
*/ */
buildId: string buildId: string
......
...@@ -65,7 +65,7 @@ export type WorkStoreContext = { ...@@ -65,7 +65,7 @@ export type WorkStoreContext = {
Partial<Pick<RenderOpts, 'reactLoadableManifest'>> Partial<Pick<RenderOpts, 'reactLoadableManifest'>>
/** /**
* The build ID of the current build. * The build or deployment ID of the current build, for cache busting of server actions.
*/ */
buildId: string buildId: string
......
...@@ -161,7 +161,7 @@ export async function setupFsCheck(opts: { ...@@ -161,7 +161,7 @@ export async function setupFsCheck(opts: {
}, },
headers: [], headers: [],
} }
let buildId = 'development' let buildId: string | undefined
let prerenderManifest: PrerenderManifest let prerenderManifest: PrerenderManifest
if (!opts.dev) { if (!opts.dev) {
...@@ -170,9 +170,6 @@ export async function setupFsCheck(opts: { ...@@ -170,9 +170,6 @@ export async function setupFsCheck(opts: {
buildId = await fs.readFile(buildIdPath, 'utf8') buildId = await fs.readFile(buildIdPath, 'utf8')
} catch (err: any) { } catch (err: any) {
if (err.code !== 'ENOENT') throw err if (err.code !== 'ENOENT') throw err
throw new Error(
`Could not find a production build in the '${opts.config.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`
)
} }
try { try {
...@@ -230,7 +227,12 @@ export async function setupFsCheck(opts: { ...@@ -230,7 +227,12 @@ export async function setupFsCheck(opts: {
const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST) const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST)
const routesManifest = JSON.parse( const routesManifest = JSON.parse(
await fs.readFile(routesManifestPath, 'utf8') await fs.readFile(routesManifestPath, 'utf8').catch((err) => {
if (err.code !== 'ENOENT') throw err
throw new Error(
`Could not find a production build in the '${opts.config.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`
)
})
) as RoutesManifest ) as RoutesManifest
prerenderManifest = JSON.parse( prerenderManifest = JSON.parse(
...@@ -266,7 +268,7 @@ export async function setupFsCheck(opts: { ...@@ -266,7 +268,7 @@ export async function setupFsCheck(opts: {
appFiles.add(appRoutesManifest[key]) appFiles.add(appRoutesManifest[key])
} }
const escapedBuildId = escapeStringRegexp(buildId) const escapedBuildId = buildId ? escapeStringRegexp(buildId) : buildId
for (const route of routesManifest.dataRoutes) { for (const route of routesManifest.dataRoutes) {
if (isDynamicRoute(route.page)) { if (isDynamicRoute(route.page)) {
...@@ -345,6 +347,8 @@ export async function setupFsCheck(opts: { ...@@ -345,6 +347,8 @@ export async function setupFsCheck(opts: {
headers: routesManifest.headers, headers: routesManifest.headers,
} }
} else { } else {
buildId = 'development'
// dev handling // dev handling
customRoutes = await loadCustomRoutes(opts.config) customRoutes = await loadCustomRoutes(opts.config)
......
...@@ -148,6 +148,38 @@ export function loadManifestFromRelativePath<T extends object>({ ...@@ -148,6 +148,38 @@ export function loadManifestFromRelativePath<T extends object>({
} }
} }
export function loadManifestFileFromRelativePath({
projectDir,
distDir,
manifest,
shouldCache,
cache,
handleMissing,
}: {
projectDir: string
distDir: string
manifest: string
shouldCache?: boolean
cache?: Map<string, unknown>
handleMissing?: boolean
}): string | undefined {
try {
const manifestPath = join(
/* turbopackIgnore: true */ projectDir,
distDir,
manifest
)
// @ts-expect-error loadManifest skipParse isn't really reflected in the type signature
return loadManifest(manifestPath, shouldCache, cache, true)
} catch (err) {
if (handleMissing) {
return undefined
}
throw err
}
}
export function clearManifestCache(path: string, cache = sharedCache): boolean { export function clearManifestCache(path: string, cache = sharedCache): boolean {
return cache.delete(path) return cache.delete(path)
} }
...@@ -2,10 +2,12 @@ import { NextDataPathnameNormalizer } from './next-data' ...@@ -2,10 +2,12 @@ import { NextDataPathnameNormalizer } from './next-data'
describe('NextDataPathnameNormalizer', () => { describe('NextDataPathnameNormalizer', () => {
describe('constructor', () => { describe('constructor', () => {
it('should error when no buildID is provided', () => { it('should error when no buildID and no deploymentId is provided', () => {
expect(() => { expect(() => {
new NextDataPathnameNormalizer('', '') new NextDataPathnameNormalizer('', '')
}).toThrowErrorMatchingInlineSnapshot(`"Invariant: buildID is required"`) }).toThrowErrorMatchingInlineSnapshot(
`"Invariant: buildID or deploymentId is required"`
)
}) })
}) })
......
...@@ -7,11 +7,10 @@ import { SuffixPathnameNormalizer } from './suffix' ...@@ -7,11 +7,10 @@ import { SuffixPathnameNormalizer } from './suffix'
export class NextDataPathnameNormalizer implements PathnameNormalizer { export class NextDataPathnameNormalizer implements PathnameNormalizer {
private readonly prefix: PrefixPathnameNormalizer private readonly prefix: PrefixPathnameNormalizer
private readonly suffix = new SuffixPathnameNormalizer('.json') private readonly suffix = new SuffixPathnameNormalizer('.json')
constructor(buildID: string, deploymentId: string) { constructor(buildID: string | undefined, deploymentId: string) {
if (!buildID) { if (!buildID && !deploymentId) {
throw new Error('Invariant: buildID is required') throw new Error('Invariant: buildID or deploymentId is required')
} }
// When deploymentId is set, data URLs don't include the build ID // When deploymentId is set, data URLs don't include the build ID
this.prefix = new PrefixPathnameNormalizer( this.prefix = new PrefixPathnameNormalizer(
deploymentId ? '/_next/data' : `/_next/data/${buildID}` deploymentId ? '/_next/data' : `/_next/data/${buildID}`
......
...@@ -301,7 +301,7 @@ export type PagesSharedContext = { ...@@ -301,7 +301,7 @@ export type PagesSharedContext = {
* Used to facilitate caching of page bundles, we send it to the client so * Used to facilitate caching of page bundles, we send it to the client so
* that pageloader knows where to load bundles. * that pageloader knows where to load bundles.
*/ */
buildId: string buildId: string | undefined
/** /**
* The deployment ID if the user is deploying to a platform that provides one. * The deployment ID if the user is deploying to a platform that provides one.
......
...@@ -103,7 +103,8 @@ export class WrappedNextRouterError { ...@@ -103,7 +103,8 @@ export class WrappedNextRouterError {
export type AppRouteModule = typeof import('../../../build/templates/app-route') export type AppRouteModule = typeof import('../../../build/templates/app-route')
export type AppRouteSharedContext = { export type AppRouteSharedContext = {
buildId: string deploymentId: string
buildId: string | undefined
} }
/** /**
...@@ -702,7 +703,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -702,7 +703,7 @@ export class AppRouteRouteModule extends RouteModule<
const staticGenerationContext: WorkStoreContext = { const staticGenerationContext: WorkStoreContext = {
page: this.definition.page, page: this.definition.page,
renderOpts: context.renderOpts, renderOpts: context.renderOpts,
buildId: context.sharedContext.buildId, buildId: context.sharedContext.deploymentId,
previouslyRevalidatedTags: [], previouslyRevalidatedTags: [],
} }
......
...@@ -182,7 +182,7 @@ export abstract class RouteModule< ...@@ -182,7 +182,7 @@ export abstract class RouteModule<
srcPage: string, srcPage: string,
projectDir?: string projectDir?: string
): { ): {
buildId: string buildId: string | undefined
buildManifest: BuildManifest buildManifest: BuildManifest
fallbackBuildManifest: BuildManifest fallbackBuildManifest: BuildManifest
routesManifest: DeepReadonly<DevRoutesManifest> routesManifest: DeepReadonly<DevRoutesManifest>
...@@ -205,7 +205,7 @@ export abstract class RouteModule< ...@@ -205,7 +205,7 @@ export abstract class RouteModule<
str ? JSON.parse(str) : undefined str ? JSON.parse(str) : undefined
result = { result = {
buildId: process.env.__NEXT_BUILD_ID || '', buildId: process.env.__NEXT_BUILD_ID,
buildManifest: self.__BUILD_MANIFEST as any, buildManifest: self.__BUILD_MANIFEST as any,
fallbackBuildManifest: {} as any, fallbackBuildManifest: {} as any,
reactLoadableManifest: maybeJSONParse(self.__REACT_LOADABLE_MANIFEST), reactLoadableManifest: maybeJSONParse(self.__REACT_LOADABLE_MANIFEST),
...@@ -249,7 +249,7 @@ export abstract class RouteModule< ...@@ -249,7 +249,7 @@ export abstract class RouteModule<
if (!projectDir) { if (!projectDir) {
throw new Error('Invariant: projectDir is required for node runtime') throw new Error('Invariant: projectDir is required for node runtime')
} }
const { loadManifestFromRelativePath } = const { loadManifestFromRelativePath, loadManifestFileFromRelativePath } =
require('../load-manifest.external') as typeof import('../load-manifest.external') require('../load-manifest.external') as typeof import('../load-manifest.external')
const normalizedPagePath = normalizePagePath(srcPage) const normalizedPagePath = normalizePagePath(srcPage)
...@@ -350,11 +350,11 @@ export abstract class RouteModule< ...@@ -350,11 +350,11 @@ export abstract class RouteModule<
}), }),
this.isDev this.isDev
? 'development' ? 'development'
: loadManifestFromRelativePath<any>({ : loadManifestFileFromRelativePath({
projectDir, projectDir,
distDir: this.distDir, distDir: this.distDir,
manifest: BUILD_ID_FILE, manifest: BUILD_ID_FILE,
skipParse: true, handleMissing: true,
}), }),
loadManifestFromRelativePath<any>({ loadManifestFromRelativePath<any>({
projectDir, projectDir,
...@@ -563,7 +563,7 @@ export abstract class RouteModule< ...@@ -563,7 +563,7 @@ export abstract class RouteModule<
} }
): Promise< ): Promise<
| { | {
buildId: string buildId: string | undefined
deploymentId: string deploymentId: string
locale?: string locale?: string
locales?: readonly string[] locales?: readonly string[]
......
...@@ -142,7 +142,8 @@ export async function adapter( ...@@ -142,7 +142,8 @@ export async function adapter(
} }
// Ensure users only see page requests, never data requests. // Ensure users only see page requests, never data requests.
let buildId = process.env.__NEXT_BUILD_ID || '' // TODO
let buildId = process.env.__NEXT_BUILD_ID
if ('buildId' in requestURL) { if ('buildId' in requestURL) {
buildId = (requestURL as NextURL).buildId || '' buildId = (requestURL as NextURL).buildId || ''
requestURL.buildId = '' requestURL.buildId = ''
......
...@@ -81,7 +81,7 @@ export class EdgeRouteModuleWrapper { ...@@ -81,7 +81,7 @@ export class EdgeRouteModuleWrapper {
caseSensitive: false, caseSensitive: false,
}) })
const { nextConfig } = this.routeModule.getNextConfigEdge( const { nextConfig, deploymentId } = this.routeModule.getNextConfigEdge(
new WebNextRequest(request) new WebNextRequest(request)
) )
...@@ -119,6 +119,7 @@ export class EdgeRouteModuleWrapper { ...@@ -119,6 +119,7 @@ export class EdgeRouteModuleWrapper {
}, },
sharedContext: { sharedContext: {
buildId: '', // TODO: Populate this properly. buildId: '', // TODO: Populate this properly.
deploymentId,
}, },
} }
......
...@@ -89,7 +89,7 @@ export type NEXT_DATA = { ...@@ -89,7 +89,7 @@ export type NEXT_DATA = {
props: Record<string, any> props: Record<string, any>
page: string page: string
query: ParsedUrlQuery query: ParsedUrlQuery
buildId: string buildId: string | undefined
assetPrefix?: string assetPrefix?: string
nextExport?: boolean nextExport?: boolean
autoExport?: boolean autoExport?: boolean
......
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