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(
const {
buildId,
deploymentId,
params,
nextConfig,
parsedUrl,
......@@ -249,6 +250,7 @@ export async function handler(
},
sharedContext: {
buildId,
deploymentId,
},
}
const nodeNextReq = new NodeNextRequest(req)
......
......@@ -37,7 +37,7 @@ export type GoodPageCache = {
}
export default class PageLoader {
private buildId: string
private buildId: string | undefined
private assetPrefix: string
private promisedSsgManifest: Promise<Set<string>>
private promisedDevPagesManifest?: Promise<string[]>
......@@ -45,7 +45,7 @@ export default class PageLoader {
public routeLoader: RouteLoader
constructor(buildId: string, assetPrefix: string) {
constructor(buildId: string | undefined, assetPrefix: string) {
this.routeLoader = createRouteLoader(assetPrefix)
this.buildId = buildId
......
......@@ -49,7 +49,8 @@ export async function exportAppRoute(
fileWriter: MultiFileWriter,
cacheComponents: boolean,
experimental: Required<Pick<ExperimentalConfig, 'authInterrupts'>>,
buildId: string
buildId: string,
deploymentId: string
): Promise<ExportRouteResult> {
// Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}`
......@@ -90,6 +91,7 @@ export async function exportAppRoute(
},
sharedContext: {
buildId,
deploymentId,
},
}
......
......@@ -248,7 +248,8 @@ async function exportPageImpl(
fileWriter,
commonRenderOpts.cacheComponents,
commonRenderOpts.experimental,
buildId
buildId,
deploymentId
)
}
......
......@@ -238,7 +238,7 @@ export type DynamicParam = {
export type GenerateFlight = typeof generateDynamicFlightRenderResult
export type AppSharedContext = {
buildId: string
buildId: string | undefined
deploymentId: string
}
......@@ -2432,7 +2432,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
renderOpts,
// @TODO move to workUnitStore of type Request
isPrefetchRequest,
buildId: sharedContext.buildId,
buildId: sharedContext.deploymentId,
previouslyRevalidatedTags,
nonce,
})
......
......@@ -95,7 +95,8 @@ export interface WorkStore {
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
......
......@@ -65,7 +65,7 @@ export type WorkStoreContext = {
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
......
......@@ -161,7 +161,7 @@ export async function setupFsCheck(opts: {
},
headers: [],
}
let buildId = 'development'
let buildId: string | undefined
let prerenderManifest: PrerenderManifest
if (!opts.dev) {
......@@ -170,9 +170,6 @@ export async function setupFsCheck(opts: {
buildId = await fs.readFile(buildIdPath, 'utf8')
} catch (err: any) {
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 {
......@@ -230,7 +227,12 @@ export async function setupFsCheck(opts: {
const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST)
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
prerenderManifest = JSON.parse(
......@@ -266,7 +268,7 @@ export async function setupFsCheck(opts: {
appFiles.add(appRoutesManifest[key])
}
const escapedBuildId = escapeStringRegexp(buildId)
const escapedBuildId = buildId ? escapeStringRegexp(buildId) : buildId
for (const route of routesManifest.dataRoutes) {
if (isDynamicRoute(route.page)) {
......@@ -345,6 +347,8 @@ export async function setupFsCheck(opts: {
headers: routesManifest.headers,
}
} else {
buildId = 'development'
// dev handling
customRoutes = await loadCustomRoutes(opts.config)
......
......@@ -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 {
return cache.delete(path)
}
......@@ -2,10 +2,12 @@ import { NextDataPathnameNormalizer } from './next-data'
describe('NextDataPathnameNormalizer', () => {
describe('constructor', () => {
it('should error when no buildID is provided', () => {
it('should error when no buildID and no deploymentId is provided', () => {
expect(() => {
new NextDataPathnameNormalizer('', '')
}).toThrowErrorMatchingInlineSnapshot(`"Invariant: buildID is required"`)
}).toThrowErrorMatchingInlineSnapshot(
`"Invariant: buildID or deploymentId is required"`
)
})
})
......
......@@ -7,11 +7,10 @@ import { SuffixPathnameNormalizer } from './suffix'
export class NextDataPathnameNormalizer implements PathnameNormalizer {
private readonly prefix: PrefixPathnameNormalizer
private readonly suffix = new SuffixPathnameNormalizer('.json')
constructor(buildID: string, deploymentId: string) {
if (!buildID) {
throw new Error('Invariant: buildID is required')
constructor(buildID: string | undefined, deploymentId: string) {
if (!buildID && !deploymentId) {
throw new Error('Invariant: buildID or deploymentId is required')
}
// When deploymentId is set, data URLs don't include the build ID
this.prefix = new PrefixPathnameNormalizer(
deploymentId ? '/_next/data' : `/_next/data/${buildID}`
......
......@@ -301,7 +301,7 @@ export type PagesSharedContext = {
* Used to facilitate caching of page bundles, we send it to the client so
* 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.
......
......@@ -103,7 +103,8 @@ export class WrappedNextRouterError {
export type AppRouteModule = typeof import('../../../build/templates/app-route')
export type AppRouteSharedContext = {
buildId: string
deploymentId: string
buildId: string | undefined
}
/**
......@@ -702,7 +703,7 @@ export class AppRouteRouteModule extends RouteModule<
const staticGenerationContext: WorkStoreContext = {
page: this.definition.page,
renderOpts: context.renderOpts,
buildId: context.sharedContext.buildId,
buildId: context.sharedContext.deploymentId,
previouslyRevalidatedTags: [],
}
......
......@@ -182,7 +182,7 @@ export abstract class RouteModule<
srcPage: string,
projectDir?: string
): {
buildId: string
buildId: string | undefined
buildManifest: BuildManifest
fallbackBuildManifest: BuildManifest
routesManifest: DeepReadonly<DevRoutesManifest>
......@@ -205,7 +205,7 @@ export abstract class RouteModule<
str ? JSON.parse(str) : undefined
result = {
buildId: process.env.__NEXT_BUILD_ID || '',
buildId: process.env.__NEXT_BUILD_ID,
buildManifest: self.__BUILD_MANIFEST as any,
fallbackBuildManifest: {} as any,
reactLoadableManifest: maybeJSONParse(self.__REACT_LOADABLE_MANIFEST),
......@@ -249,7 +249,7 @@ export abstract class RouteModule<
if (!projectDir) {
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')
const normalizedPagePath = normalizePagePath(srcPage)
......@@ -350,11 +350,11 @@ export abstract class RouteModule<
}),
this.isDev
? 'development'
: loadManifestFromRelativePath<any>({
: loadManifestFileFromRelativePath({
projectDir,
distDir: this.distDir,
manifest: BUILD_ID_FILE,
skipParse: true,
handleMissing: true,
}),
loadManifestFromRelativePath<any>({
projectDir,
......@@ -563,7 +563,7 @@ export abstract class RouteModule<
}
): Promise<
| {
buildId: string
buildId: string | undefined
deploymentId: string
locale?: string
locales?: readonly string[]
......
......@@ -142,7 +142,8 @@ export async function adapter(
}
// 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) {
buildId = (requestURL as NextURL).buildId || ''
requestURL.buildId = ''
......
......@@ -81,7 +81,7 @@ export class EdgeRouteModuleWrapper {
caseSensitive: false,
})
const { nextConfig } = this.routeModule.getNextConfigEdge(
const { nextConfig, deploymentId } = this.routeModule.getNextConfigEdge(
new WebNextRequest(request)
)
......@@ -119,6 +119,7 @@ export class EdgeRouteModuleWrapper {
},
sharedContext: {
buildId: '', // TODO: Populate this properly.
deploymentId,
},
}
......
......@@ -89,7 +89,7 @@ export type NEXT_DATA = {
props: Record<string, any>
page: string
query: ParsedUrlQuery
buildId: string
buildId: string | undefined
assetPrefix?: string
nextExport?: 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