Unverified Commit 03a1815a authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Inject `<html data-dpl-id>` and don't inline it into JS anymore (#88761)

We don't inline `process.env.NEXT_DEPLOYMENT_ID` anymore into browser chunks, and instead read it from `<html data-dpl-id` attribute at runtime.

Closes PACK-6538

- [x] ~~Causes a hydration error at the moment.~~ Solved by removing the attribute immediately before hydration happens
<img width="1443" height="620" alt="Bildschirmfoto 2026-01-20 um 12 32 06" src="https://github.com/user-attachments/assets/b69b3a0b-129d-44f4-84d1-10572b650437" />
parent eb14325e
...@@ -177,12 +177,10 @@ export function getDefineEnv({ ...@@ -177,12 +177,10 @@ export function getDefineEnv({
: isClient : isClient
? isTurbopack ? isTurbopack
? { ? {
// This is set at runtime by packages/next/src/client/register-deployment-id-global.ts
'process.env.NEXT_DEPLOYMENT_ID': { 'process.env.NEXT_DEPLOYMENT_ID': {
[DEFINE_ENV_EXPRESSION]: 'globalThis.NEXT_DEPLOYMENT_ID', [DEFINE_ENV_EXPRESSION]: 'globalThis.NEXT_DEPLOYMENT_ID',
}, },
// TODO replace with read from HTML document attribute
'process.env.NEXT_DEPLOYMENT_ID_COMPILE_TIME':
config.deploymentId,
} }
: { : {
// For Webpack, we currently don't use the non-inlining globalThis.NEXT_DEPLOYMENT_ID // For Webpack, we currently don't use the non-inlining globalThis.NEXT_DEPLOYMENT_ID
......
...@@ -928,13 +928,24 @@ export function Html( ...@@ -928,13 +928,24 @@ export function Html(
HTMLHtmlElement HTMLHtmlElement
> >
) { ) {
const { docComponentsRendered, locale, scriptLoader, __NEXT_DATA__ } = const {
useHtmlContext() docComponentsRendered,
locale,
scriptLoader,
deploymentId,
__NEXT_DATA__,
} = useHtmlContext()
docComponentsRendered.Html = true docComponentsRendered.Html = true
handleDocumentScriptLoaderItems(scriptLoader, __NEXT_DATA__, props) handleDocumentScriptLoaderItems(scriptLoader, __NEXT_DATA__, props)
return <html {...props} lang={props.lang || locale || undefined} /> return (
<html
{...props}
lang={props.lang || locale || undefined}
data-dpl-id={deploymentId || undefined}
/>
)
} }
export function Main() { export function Main() {
......
...@@ -2884,6 +2884,7 @@ async function renderToStream( ...@@ -2884,6 +2884,7 @@ async function renderToStream(
), ),
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}) })
} }
} }
...@@ -2961,6 +2962,7 @@ async function renderToStream( ...@@ -2961,6 +2962,7 @@ async function renderToStream(
isStaticGeneration: generateStaticHTML, isStaticGeneration: generateStaticHTML,
isBuildTimePrerendering: ctx.workStore.isBuildTimePrerendering === true, isBuildTimePrerendering: ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId, buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
validateRootLayout: dev, validateRootLayout: dev,
...@@ -3130,6 +3132,7 @@ async function renderToStream( ...@@ -3130,6 +3132,7 @@ async function renderToStream(
isBuildTimePrerendering: isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true, ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId, buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
getServerInsertedHTML: makeGetServerInsertedHTML({ getServerInsertedHTML: makeGetServerInsertedHTML({
polyfills, polyfills,
renderServerInsertedHTML, renderServerInsertedHTML,
...@@ -4839,6 +4842,7 @@ async function prerenderToStream( ...@@ -4839,6 +4842,7 @@ async function prerenderToStream(
stream: await continueDynamicPrerender(prelude, { stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}), }),
dynamicAccess: consumeDynamicAccess( dynamicAccess: consumeDynamicAccess(
serverDynamicTracking, serverDynamicTracking,
...@@ -4934,6 +4938,7 @@ async function prerenderToStream( ...@@ -4934,6 +4938,7 @@ async function prerenderToStream(
isBuildTimePrerendering: isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true, ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId, buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
}) })
} else { } else {
// Normal static prerender case, no fallback param handling needed // Normal static prerender case, no fallback param handling needed
...@@ -4948,6 +4953,7 @@ async function prerenderToStream( ...@@ -4948,6 +4953,7 @@ async function prerenderToStream(
isBuildTimePrerendering: isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true, ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId, buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
}) })
} }
...@@ -5119,6 +5125,7 @@ async function prerenderToStream( ...@@ -5119,6 +5125,7 @@ async function prerenderToStream(
stream: await continueDynamicPrerender(prelude, { stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}), }),
dynamicAccess: dynamicTracking.dynamicAccesses, dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass? // TODO: Should this include the SSR pass?
...@@ -5140,6 +5147,7 @@ async function prerenderToStream( ...@@ -5140,6 +5147,7 @@ async function prerenderToStream(
stream: await continueDynamicPrerender(prelude, { stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}), }),
dynamicAccess: dynamicTracking.dynamicAccesses, dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass? // TODO: Should this include the SSR pass?
...@@ -5206,6 +5214,7 @@ async function prerenderToStream( ...@@ -5206,6 +5214,7 @@ async function prerenderToStream(
isBuildTimePrerendering: isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true, ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId, buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
}), }),
dynamicAccess: dynamicTracking.dynamicAccesses, dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass? // TODO: Should this include the SSR pass?
...@@ -5306,6 +5315,7 @@ async function prerenderToStream( ...@@ -5306,6 +5315,7 @@ async function prerenderToStream(
buildId: ctx.workStore.buildId, buildId: ctx.workStore.buildId,
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}), }),
// TODO: Should this include the SSR pass? // TODO: Should this include the SSR pass?
collectedRevalidate: prerenderLegacyStore.revalidate, collectedRevalidate: prerenderLegacyStore.revalidate,
...@@ -5491,6 +5501,7 @@ async function prerenderToStream( ...@@ -5491,6 +5501,7 @@ async function prerenderToStream(
}), }),
getServerInsertedMetadata, getServerInsertedMetadata,
validateRootLayout: dev, validateRootLayout: dev,
deploymentId: ctx.renderOpts.deploymentId,
}), }),
dynamicAccess: null, dynamicAccess: null,
collectedRevalidate: collectedRevalidate:
......
...@@ -1499,6 +1499,7 @@ export async function renderToHTMLImpl( ...@@ -1499,6 +1499,7 @@ export async function renderToHTMLImpl(
docComponentsRendered, docComponentsRendered,
dangerousAsPath: router.asPath, dangerousAsPath: router.asPath,
isDevelopment: !!dev, isDevelopment: !!dev,
deploymentId: sharedContext.deploymentId,
dynamicImports: Array.from(dynamicImports), dynamicImports: Array.from(dynamicImports),
dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []), dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []),
assetPrefix, assetPrefix,
......
...@@ -725,6 +725,48 @@ function createStripDocumentClosingTagsTransform(): TransformStream< ...@@ -725,6 +725,48 @@ function createStripDocumentClosingTagsTransform(): TransformStream<
}) })
} }
function createHtmlDataDplIdTransformStream(
dplId: string
): TransformStream<Uint8Array, Uint8Array> {
let didTransform = false
return new TransformStream({
transform(chunk, controller) {
if (didTransform) {
controller.enqueue(chunk)
return
}
const htmlTagIndex = indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML)
if (htmlTagIndex === -1) {
controller.enqueue(chunk)
return
}
// Insert the data-dpl-id attribute right after "<html "
const insertionPoint = htmlTagIndex + ENCODED_TAGS.OPENING.HTML.length
const attribute = ` data-dpl-id="${dplId}"`
const encodedAttribute = encoder.encode(attribute)
const modifiedChunk = new Uint8Array(
chunk.length + encodedAttribute.length
)
// Copy everything before the insertion point
modifiedChunk.set(chunk.subarray(0, insertionPoint))
// Insert the attribute
modifiedChunk.set(encodedAttribute, insertionPoint)
// Copy everything after
modifiedChunk.set(
chunk.subarray(insertionPoint),
insertionPoint + encodedAttribute.length
)
controller.enqueue(modifiedChunk)
didTransform = true
},
})
}
/* /*
* Checks if the root layout is missing the html or body tags * Checks if the root layout is missing the html or body tags
* and if so, it will inject a script tag to throw an error in the browser, showing the user * and if so, it will inject a script tag to throw an error in the browser, showing the user
...@@ -799,6 +841,7 @@ export type ContinueStreamOptions = { ...@@ -799,6 +841,7 @@ export type ContinueStreamOptions = {
isStaticGeneration: boolean isStaticGeneration: boolean
isBuildTimePrerendering: boolean isBuildTimePrerendering: boolean
buildId: string buildId: string
deploymentId: string | undefined
getServerInsertedHTML: () => Promise<string> getServerInsertedHTML: () => Promise<string>
getServerInsertedMetadata: () => Promise<string> getServerInsertedMetadata: () => Promise<string>
validateRootLayout?: boolean validateRootLayout?: boolean
...@@ -816,6 +859,7 @@ export async function continueFizzStream( ...@@ -816,6 +859,7 @@ export async function continueFizzStream(
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
buildId, buildId,
deploymentId,
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
validateRootLayout, validateRootLayout,
...@@ -840,6 +884,9 @@ export async function continueFizzStream( ...@@ -840,6 +884,9 @@ export async function continueFizzStream(
// Add build id comment to start of the HTML document (in export mode) // Add build id comment to start of the HTML document (in export mode)
createPrefetchCommentStream(isBuildTimePrerendering, buildId), createPrefetchCommentStream(isBuildTimePrerendering, buildId),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Transform metadata // Transform metadata
createMetadataTransformStream(getServerInsertedMetadata), createMetadataTransformStream(getServerInsertedMetadata),
...@@ -869,6 +916,7 @@ export async function continueFizzStream( ...@@ -869,6 +916,7 @@ export async function continueFizzStream(
type ContinueDynamicPrerenderOptions = { type ContinueDynamicPrerenderOptions = {
getServerInsertedHTML: () => Promise<string> getServerInsertedHTML: () => Promise<string>
getServerInsertedMetadata: () => Promise<string> getServerInsertedMetadata: () => Promise<string>
deploymentId: string | undefined
} }
export async function continueDynamicPrerender( export async function continueDynamicPrerender(
...@@ -876,18 +924,20 @@ export async function continueDynamicPrerender( ...@@ -876,18 +924,20 @@ export async function continueDynamicPrerender(
{ {
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
deploymentId,
}: ContinueDynamicPrerenderOptions }: ContinueDynamicPrerenderOptions
) { ) {
return ( return chainTransformers(prerenderStream, [
prerenderStream
// Buffer everything to avoid flushing too frequently // Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream()) createBufferedTransformStream(),
.pipeThrough(createStripDocumentClosingTagsTransform()) createStripDocumentClosingTagsTransform(),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Insert generated tags to head // Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML)) createHeadInsertionTransformStream(getServerInsertedHTML),
// Transform metadata // Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata)) createMetadataTransformStream(getServerInsertedMetadata),
) ])
} }
type ContinueStaticPrerenderOptions = { type ContinueStaticPrerenderOptions = {
...@@ -896,6 +946,7 @@ type ContinueStaticPrerenderOptions = { ...@@ -896,6 +946,7 @@ type ContinueStaticPrerenderOptions = {
getServerInsertedMetadata: () => Promise<string> getServerInsertedMetadata: () => Promise<string>
isBuildTimePrerendering: boolean isBuildTimePrerendering: boolean
buildId: string buildId: string
deploymentId: string | undefined
} }
export async function continueStaticPrerender( export async function continueStaticPrerender(
...@@ -906,27 +957,25 @@ export async function continueStaticPrerender( ...@@ -906,27 +957,25 @@ export async function continueStaticPrerender(
getServerInsertedMetadata, getServerInsertedMetadata,
isBuildTimePrerendering, isBuildTimePrerendering,
buildId, buildId,
deploymentId,
}: ContinueStaticPrerenderOptions }: ContinueStaticPrerenderOptions
) { ) {
return ( return chainTransformers(prerenderStream, [
prerenderStream
// Buffer everything to avoid flushing too frequently // Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream()) createBufferedTransformStream(),
// Add build id comment to start of the HTML document (in export mode) // Add build id comment to start of the HTML document (in export mode)
.pipeThrough( createPrefetchCommentStream(isBuildTimePrerendering, buildId),
createPrefetchCommentStream(isBuildTimePrerendering, buildId) // Insert data-dpl-id attribute on the html tag
) deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Insert generated tags to head // Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML)) createHeadInsertionTransformStream(getServerInsertedHTML),
// Transform metadata // Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata)) createMetadataTransformStream(getServerInsertedMetadata),
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML // Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough( createFlightDataInjectionTransformStream(inlinedDataStream, true),
createFlightDataInjectionTransformStream(inlinedDataStream, true)
)
// Close tags should always be deferred to the end // Close tags should always be deferred to the end
.pipeThrough(createMoveSuffixStream()) createMoveSuffixStream(),
) ])
} }
export async function continueStaticFallbackPrerender( export async function continueStaticFallbackPrerender(
...@@ -937,32 +986,30 @@ export async function continueStaticFallbackPrerender( ...@@ -937,32 +986,30 @@ export async function continueStaticFallbackPrerender(
getServerInsertedMetadata, getServerInsertedMetadata,
isBuildTimePrerendering, isBuildTimePrerendering,
buildId, buildId,
deploymentId,
}: ContinueStaticPrerenderOptions }: ContinueStaticPrerenderOptions
) { ) {
// Same as `continueStaticPrerender`, but also inserts an additional script // Same as `continueStaticPrerender`, but also inserts an additional script
// to instruct the client to start fetching the hydration data as early // to instruct the client to start fetching the hydration data as early
// as possible. // as possible.
return ( return chainTransformers(prerenderStream, [
prerenderStream
// Buffer everything to avoid flushing too frequently // Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream()) createBufferedTransformStream(),
// Add build id comment to start of the HTML document (in export mode) // Add build id comment to start of the HTML document (in export mode)
.pipeThrough( createPrefetchCommentStream(isBuildTimePrerendering, buildId),
createPrefetchCommentStream(isBuildTimePrerendering, buildId) // Insert data-dpl-id attribute on the html tag
) deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Insert generated tags to head // Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML)) createHeadInsertionTransformStream(getServerInsertedHTML),
// Insert the client resume script into the head // Insert the client resume script into the head
.pipeThrough(createClientResumeScriptInsertionTransformStream()) createClientResumeScriptInsertionTransformStream(),
// Transform metadata // Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata)) createMetadataTransformStream(getServerInsertedMetadata),
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML // Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough( createFlightDataInjectionTransformStream(inlinedDataStream, true),
createFlightDataInjectionTransformStream(inlinedDataStream, true)
)
// Close tags should always be deferred to the end // Close tags should always be deferred to the end
.pipeThrough(createMoveSuffixStream()) createMoveSuffixStream(),
) ])
} }
type ContinueResumeOptions = { type ContinueResumeOptions = {
...@@ -970,6 +1017,7 @@ type ContinueResumeOptions = { ...@@ -970,6 +1017,7 @@ type ContinueResumeOptions = {
getServerInsertedHTML: () => Promise<string> getServerInsertedHTML: () => Promise<string>
getServerInsertedMetadata: () => Promise<string> getServerInsertedMetadata: () => Promise<string>
delayDataUntilFirstHtmlChunk: boolean delayDataUntilFirstHtmlChunk: boolean
deploymentId: string | undefined
} }
export async function continueDynamicHTMLResume( export async function continueDynamicHTMLResume(
...@@ -979,26 +1027,26 @@ export async function continueDynamicHTMLResume( ...@@ -979,26 +1027,26 @@ export async function continueDynamicHTMLResume(
inlinedDataStream, inlinedDataStream,
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
deploymentId,
}: ContinueResumeOptions }: ContinueResumeOptions
) { ) {
return ( return chainTransformers(renderStream, [
renderStream
// Buffer everything to avoid flushing too frequently // Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream()) createBufferedTransformStream(),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Insert generated tags to head // Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML)) createHeadInsertionTransformStream(getServerInsertedHTML),
// Transform metadata // Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata)) createMetadataTransformStream(getServerInsertedMetadata),
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML // Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(
createFlightDataInjectionTransformStream( createFlightDataInjectionTransformStream(
inlinedDataStream, inlinedDataStream,
delayDataUntilFirstHtmlChunk delayDataUntilFirstHtmlChunk
) ),
)
// Close tags should always be deferred to the end // Close tags should always be deferred to the end
.pipeThrough(createMoveSuffixStream()) createMoveSuffixStream(),
) ])
} }
export function createDocumentClosingStream(): ReadableStream<Uint8Array> { export function createDocumentClosingStream(): ReadableStream<Uint8Array> {
......
// This could also be a variable instead of a function, but some unit tests want to change the ID at let deploymentId: string | undefined
// runtime. Even though that would never happen in a real deployment.
if (typeof window !== 'undefined') {
deploymentId = document.documentElement.dataset.dplId
// Immediately remove the attribute to prevent hydration errors (the dplId was inserted into the
// HTML only), React isn't aware of it at all.
delete document.documentElement.dataset.dplId
} else {
// Client side: replaced with globalThis.NEXT_DEPLOYMENT_ID
// Server side: left as is or replaced with a string or replaced with false
deploymentId = process.env.NEXT_DEPLOYMENT_ID || undefined
}
export function getDeploymentId(): string | undefined { export function getDeploymentId(): string | undefined {
return ( return deploymentId
process.env.NEXT_DEPLOYMENT_ID ??
process.env.NEXT_DEPLOYMENT_ID_COMPILE_TIME
)
} }
export function getDeploymentIdQueryOrEmptyString(): string { export function getDeploymentIdQueryOrEmptyString(): string {
let deploymentId = getDeploymentId()
if (deploymentId) { if (deploymentId) {
return `?dpl=${deploymentId}` return `?dpl=${deploymentId}`
} }
......
...@@ -18,6 +18,7 @@ export type HtmlProps = { ...@@ -18,6 +18,7 @@ export type HtmlProps = {
} }
buildManifest: BuildManifest buildManifest: BuildManifest
isDevelopment: boolean isDevelopment: boolean
deploymentId: string | undefined
dynamicImports: string[] dynamicImports: string[]
/** /**
* This manifest is only needed for Pages dir, Production, Webpack * This manifest is only needed for Pages dir, Production, Webpack
......
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