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({
: isClient
? isTurbopack
? {
// This is set at runtime by packages/next/src/client/register-deployment-id-global.ts
'process.env.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
......
......@@ -928,13 +928,24 @@ export function Html(
HTMLHtmlElement
>
) {
const { docComponentsRendered, locale, scriptLoader, __NEXT_DATA__ } =
useHtmlContext()
const {
docComponentsRendered,
locale,
scriptLoader,
deploymentId,
__NEXT_DATA__,
} = useHtmlContext()
docComponentsRendered.Html = true
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() {
......
......@@ -2884,6 +2884,7 @@ async function renderToStream(
),
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
})
}
}
......@@ -2961,6 +2962,7 @@ async function renderToStream(
isStaticGeneration: generateStaticHTML,
isBuildTimePrerendering: ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
getServerInsertedHTML,
getServerInsertedMetadata,
validateRootLayout: dev,
......@@ -3130,6 +3132,7 @@ async function renderToStream(
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
getServerInsertedHTML: makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
......@@ -4839,6 +4842,7 @@ async function prerenderToStream(
stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}),
dynamicAccess: consumeDynamicAccess(
serverDynamicTracking,
......@@ -4934,6 +4938,7 @@ async function prerenderToStream(
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
})
} else {
// Normal static prerender case, no fallback param handling needed
......@@ -4948,6 +4953,7 @@ async function prerenderToStream(
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
})
}
......@@ -5119,6 +5125,7 @@ async function prerenderToStream(
stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}),
dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass?
......@@ -5140,6 +5147,7 @@ async function prerenderToStream(
stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}),
dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass?
......@@ -5206,6 +5214,7 @@ async function prerenderToStream(
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
deploymentId: ctx.renderOpts.deploymentId,
}),
dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass?
......@@ -5306,6 +5315,7 @@ async function prerenderToStream(
buildId: ctx.workStore.buildId,
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId: ctx.renderOpts.deploymentId,
}),
// TODO: Should this include the SSR pass?
collectedRevalidate: prerenderLegacyStore.revalidate,
......@@ -5491,6 +5501,7 @@ async function prerenderToStream(
}),
getServerInsertedMetadata,
validateRootLayout: dev,
deploymentId: ctx.renderOpts.deploymentId,
}),
dynamicAccess: null,
collectedRevalidate:
......
......@@ -1499,6 +1499,7 @@ export async function renderToHTMLImpl(
docComponentsRendered,
dangerousAsPath: router.asPath,
isDevelopment: !!dev,
deploymentId: sharedContext.deploymentId,
dynamicImports: Array.from(dynamicImports),
dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []),
assetPrefix,
......
......@@ -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
* 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 = {
isStaticGeneration: boolean
isBuildTimePrerendering: boolean
buildId: string
deploymentId: string | undefined
getServerInsertedHTML: () => Promise<string>
getServerInsertedMetadata: () => Promise<string>
validateRootLayout?: boolean
......@@ -816,6 +859,7 @@ export async function continueFizzStream(
isStaticGeneration,
isBuildTimePrerendering,
buildId,
deploymentId,
getServerInsertedHTML,
getServerInsertedMetadata,
validateRootLayout,
......@@ -840,6 +884,9 @@ export async function continueFizzStream(
// Add build id comment to start of the HTML document (in export mode)
createPrefetchCommentStream(isBuildTimePrerendering, buildId),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Transform metadata
createMetadataTransformStream(getServerInsertedMetadata),
......@@ -869,6 +916,7 @@ export async function continueFizzStream(
type ContinueDynamicPrerenderOptions = {
getServerInsertedHTML: () => Promise<string>
getServerInsertedMetadata: () => Promise<string>
deploymentId: string | undefined
}
export async function continueDynamicPrerender(
......@@ -876,18 +924,20 @@ export async function continueDynamicPrerender(
{
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId,
}: ContinueDynamicPrerenderOptions
) {
return (
prerenderStream
// Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream())
.pipeThrough(createStripDocumentClosingTagsTransform())
// Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
)
return chainTransformers(prerenderStream, [
// Buffer everything to avoid flushing too frequently
createBufferedTransformStream(),
createStripDocumentClosingTagsTransform(),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Insert generated tags to head
createHeadInsertionTransformStream(getServerInsertedHTML),
// Transform metadata
createMetadataTransformStream(getServerInsertedMetadata),
])
}
type ContinueStaticPrerenderOptions = {
......@@ -896,6 +946,7 @@ type ContinueStaticPrerenderOptions = {
getServerInsertedMetadata: () => Promise<string>
isBuildTimePrerendering: boolean
buildId: string
deploymentId: string | undefined
}
export async function continueStaticPrerender(
......@@ -906,27 +957,25 @@ export async function continueStaticPrerender(
getServerInsertedMetadata,
isBuildTimePrerendering,
buildId,
deploymentId,
}: ContinueStaticPrerenderOptions
) {
return (
prerenderStream
// Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream())
// Add build id comment to start of the HTML document (in export mode)
.pipeThrough(
createPrefetchCommentStream(isBuildTimePrerendering, buildId)
)
// Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(
createFlightDataInjectionTransformStream(inlinedDataStream, true)
)
// Close tags should always be deferred to the end
.pipeThrough(createMoveSuffixStream())
)
return chainTransformers(prerenderStream, [
// Buffer everything to avoid flushing too frequently
createBufferedTransformStream(),
// Add build id comment to start of the HTML document (in export mode)
createPrefetchCommentStream(isBuildTimePrerendering, buildId),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Insert generated tags to head
createHeadInsertionTransformStream(getServerInsertedHTML),
// Transform metadata
createMetadataTransformStream(getServerInsertedMetadata),
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
createFlightDataInjectionTransformStream(inlinedDataStream, true),
// Close tags should always be deferred to the end
createMoveSuffixStream(),
])
}
export async function continueStaticFallbackPrerender(
......@@ -937,32 +986,30 @@ export async function continueStaticFallbackPrerender(
getServerInsertedMetadata,
isBuildTimePrerendering,
buildId,
deploymentId,
}: ContinueStaticPrerenderOptions
) {
// Same as `continueStaticPrerender`, but also inserts an additional script
// to instruct the client to start fetching the hydration data as early
// as possible.
return (
prerenderStream
// Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream())
// Add build id comment to start of the HTML document (in export mode)
.pipeThrough(
createPrefetchCommentStream(isBuildTimePrerendering, buildId)
)
// Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Insert the client resume script into the head
.pipeThrough(createClientResumeScriptInsertionTransformStream())
// Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(
createFlightDataInjectionTransformStream(inlinedDataStream, true)
)
// Close tags should always be deferred to the end
.pipeThrough(createMoveSuffixStream())
)
return chainTransformers(prerenderStream, [
// Buffer everything to avoid flushing too frequently
createBufferedTransformStream(),
// Add build id comment to start of the HTML document (in export mode)
createPrefetchCommentStream(isBuildTimePrerendering, buildId),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Insert generated tags to head
createHeadInsertionTransformStream(getServerInsertedHTML),
// Insert the client resume script into the head
createClientResumeScriptInsertionTransformStream(),
// Transform metadata
createMetadataTransformStream(getServerInsertedMetadata),
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
createFlightDataInjectionTransformStream(inlinedDataStream, true),
// Close tags should always be deferred to the end
createMoveSuffixStream(),
])
}
type ContinueResumeOptions = {
......@@ -970,6 +1017,7 @@ type ContinueResumeOptions = {
getServerInsertedHTML: () => Promise<string>
getServerInsertedMetadata: () => Promise<string>
delayDataUntilFirstHtmlChunk: boolean
deploymentId: string | undefined
}
export async function continueDynamicHTMLResume(
......@@ -979,26 +1027,26 @@ export async function continueDynamicHTMLResume(
inlinedDataStream,
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId,
}: ContinueResumeOptions
) {
return (
renderStream
// Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream())
// Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(
createFlightDataInjectionTransformStream(
inlinedDataStream,
delayDataUntilFirstHtmlChunk
)
)
// Close tags should always be deferred to the end
.pipeThrough(createMoveSuffixStream())
)
return chainTransformers(renderStream, [
// Buffer everything to avoid flushing too frequently
createBufferedTransformStream(),
// Insert data-dpl-id attribute on the html tag
deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,
// Insert generated tags to head
createHeadInsertionTransformStream(getServerInsertedHTML),
// Transform metadata
createMetadataTransformStream(getServerInsertedMetadata),
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
createFlightDataInjectionTransformStream(
inlinedDataStream,
delayDataUntilFirstHtmlChunk
),
// Close tags should always be deferred to the end
createMoveSuffixStream(),
])
}
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
// runtime. Even though that would never happen in a real deployment.
let deploymentId: string | undefined
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 {
return (
process.env.NEXT_DEPLOYMENT_ID ??
process.env.NEXT_DEPLOYMENT_ID_COMPILE_TIME
)
return deploymentId
}
export function getDeploymentIdQueryOrEmptyString(): string {
let deploymentId = getDeploymentId()
if (deploymentId) {
return `?dpl=${deploymentId}`
}
......
......@@ -18,6 +18,7 @@ export type HtmlProps = {
}
buildManifest: BuildManifest
isDevelopment: boolean
deploymentId: string | undefined
dynamicImports: string[]
/**
* 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