Unverified Commit 199aa3c8 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add strict next head handling (#47938)

This adds an `experimental.strictNextHead` flag to allow updating head
tags tracking for pages to resolve the issue with runtime scripts being
appended to the head element breaking the head tracking.

Fixes: https://github.com/vercel/next.js/issues/11012
Fixes: https://github.com/vercel/next.js/issues/20682
x-ref: [slack
thread](https://vercel.slack.com/archives/C051B8JAPQ9/p1680156608831939)
parent 34ceeb5d
...@@ -152,6 +152,7 @@ export default function startHandler({ ...@@ -152,6 +152,7 @@ export default function startHandler({
: Component; : Component;
const renderOpts: RenderOpts = { const renderOpts: RenderOpts = {
strictNextHead: false,
/* LoadComponentsReturnType */ /* LoadComponentsReturnType */
Component: comp, Component: comp,
App, App,
......
...@@ -319,6 +319,9 @@ export function getDefineEnv({ ...@@ -319,6 +319,9 @@ export function getDefineEnv({
: {}), : {}),
}), }),
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath), 'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
'process.env.__NEXT_STRICT_NEXT_HEAD': JSON.stringify(
config.experimental.strictNextHead
),
'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites), 'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites),
'process.env.__NEXT_CONFIG_OUTPUT': JSON.stringify(config.output), 'process.env.__NEXT_CONFIG_OUTPUT': JSON.stringify(config.output),
'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n), 'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n),
......
...@@ -70,7 +70,65 @@ export function isEqualNode(oldTag: Element, newTag: Element) { ...@@ -70,7 +70,65 @@ export function isEqualNode(oldTag: Element, newTag: Element) {
return oldTag.isEqualNode(newTag) return oldTag.isEqualNode(newTag)
} }
function updateElements(type: string, components: JSX.Element[]): void { let updateElements: (type: string, components: JSX.Element[]) => void
if (process.env.__NEXT_STRICT_NEXT_HEAD) {
updateElements = (type: string, components: JSX.Element[]) => {
const headEl = document.querySelector('head')
if (!headEl) return
const headMetaTags = headEl.querySelectorAll('meta[name="next-head"]') || []
const oldTags: Element[] = []
if (type === 'meta') {
const metaCharset = headEl.querySelector('meta[charset]')
if (metaCharset) {
oldTags.push(metaCharset)
}
}
for (let i = 0; i < headMetaTags.length; i++) {
const metaTag = headMetaTags[i]
const headTag = metaTag.nextSibling as Element
if (headTag?.tagName?.toLowerCase() === type) {
oldTags.push(headTag)
}
}
const newTags = (components.map(reactElementToDOM) as HTMLElement[]).filter(
(newTag) => {
for (let k = 0, len = oldTags.length; k < len; k++) {
const oldTag = oldTags[k]
if (isEqualNode(oldTag, newTag)) {
oldTags.splice(k, 1)
return false
}
}
return true
}
)
oldTags.forEach((t) => {
const metaTag = t.previousSibling as Element
if (metaTag && metaTag.getAttribute('name') === 'next-head') {
t.parentNode?.removeChild(metaTag)
}
t.parentNode?.removeChild(t)
})
newTags.forEach((t) => {
const meta = document.createElement('meta')
meta.name = 'next-head'
meta.content = '1'
// meta[charset] must be first element so special case
if (!(t.tagName?.toLowerCase() === 'meta' && t.getAttribute('charset'))) {
headEl.appendChild(meta)
}
headEl.appendChild(t)
})
}
} else {
updateElements = (type: string, components: JSX.Element[]) => {
const headEl = document.getElementsByTagName('head')[0] const headEl = document.getElementsByTagName('head')[0]
const headCountEl: HTMLMetaElement = headEl.querySelector( const headCountEl: HTMLMetaElement = headEl.querySelector(
'meta[name=next-head-count]' 'meta[name=next-head-count]'
...@@ -111,7 +169,12 @@ function updateElements(type: string, components: JSX.Element[]): void { ...@@ -111,7 +169,12 @@ function updateElements(type: string, components: JSX.Element[]): void {
oldTags.forEach((t) => t.parentNode?.removeChild(t)) oldTags.forEach((t) => t.parentNode?.removeChild(t))
newTags.forEach((t) => headEl.insertBefore(t, headCountEl)) newTags.forEach((t) => headEl.insertBefore(t, headCountEl))
headCountEl.content = (headCount - oldTags.length + newTags.length).toString() headCountEl.content = (
headCount -
oldTags.length +
newTags.length
).toString()
}
} }
export default function initHeadManager(): { export default function initHeadManager(): {
......
...@@ -488,6 +488,7 @@ export default async function exportApp( ...@@ -488,6 +488,7 @@ export default async function exportApp(
)), )),
} }
: {}), : {}),
strictNextHead: !!nextConfig.experimental.strictNextHead,
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......
...@@ -124,6 +124,7 @@ interface RenderOpts { ...@@ -124,6 +124,7 @@ interface RenderOpts {
trailingSlash?: boolean trailingSlash?: boolean
supportsDynamicHTML?: boolean supportsDynamicHTML?: boolean
incrementalCache?: IncrementalCache incrementalCache?: IncrementalCache
strictNextHead?: boolean
} }
// expose AsyncLocalStorage on globalThis for react usage // expose AsyncLocalStorage on globalThis for react usage
...@@ -325,6 +326,7 @@ export default async function exportPage({ ...@@ -325,6 +326,7 @@ export default async function exportPage({
curRenderOpts = { curRenderOpts = {
...components, ...components,
...renderOpts, ...renderOpts,
strictNextHead: !!renderOpts.strictNextHead,
ampPath: renderAmpPath, ampPath: renderAmpPath,
params, params,
optimizeFonts, optimizeFonts,
......
...@@ -683,15 +683,30 @@ export class Head extends React.Component<HeadProps> { ...@@ -683,15 +683,30 @@ export class Head extends React.Component<HeadProps> {
let otherHeadElements: Array<JSX.Element> = [] let otherHeadElements: Array<JSX.Element> = []
if (head) { if (head) {
head.forEach((c) => { head.forEach((c) => {
let metaTag
if (this.context.strictNextHead) {
metaTag = React.createElement('meta', {
name: 'next-head',
content: '1',
})
}
if ( if (
c && c &&
c.type === 'link' && c.type === 'link' &&
c.props['rel'] === 'preload' && c.props['rel'] === 'preload' &&
c.props['as'] === 'style' c.props['as'] === 'style'
) { ) {
metaTag && cssPreloads.push(metaTag)
cssPreloads.push(c) cssPreloads.push(c)
} else { } else {
c && otherHeadElements.push(c) if (c) {
if (metaTag && (c.type !== 'meta' || !c.props['charSet'])) {
otherHeadElements.push(metaTag)
}
otherHeadElements.push(c)
}
} }
}) })
head = cssPreloads.concat(otherHeadElements) head = cssPreloads.concat(otherHeadElements)
...@@ -822,10 +837,12 @@ export class Head extends React.Component<HeadProps> { ...@@ -822,10 +837,12 @@ export class Head extends React.Component<HeadProps> {
</> </>
)} )}
{head} {head}
{this.context.strictNextHead ? null : (
<meta <meta
name="next-head-count" name="next-head-count"
content={React.Children.count(head || []).toString()} content={React.Children.count(head || []).toString()}
/> />
)}
{children} {children}
{optimizeFonts && <meta name="next-font-preconnect" />} {optimizeFonts && <meta name="next-font-preconnect" />}
......
...@@ -247,6 +247,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -247,6 +247,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
serverComponentProps?: any serverComponentProps?: any
largePageDataBytes?: number largePageDataBytes?: number
appDirDevErrorLogger?: (err: any) => Promise<void> appDirDevErrorLogger?: (err: any) => Promise<void>
strictNextHead: boolean
} }
protected serverOptions: ServerOptions protected serverOptions: ServerOptions
private responseCache: ResponseCacheBase private responseCache: ResponseCacheBase
...@@ -412,6 +413,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -412,6 +413,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.nextFontManifest = this.getNextFontManifest() this.nextFontManifest = this.getNextFontManifest()
this.renderOpts = { this.renderOpts = {
strictNextHead: !!this.nextConfig.experimental.strictNextHead,
poweredByHeader: this.nextConfig.poweredByHeader, poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase || '', canonicalBase: this.nextConfig.amp.canonicalBase || '',
buildId: this.buildId, buildId: this.buildId,
......
...@@ -396,6 +396,9 @@ const configSchema = { ...@@ -396,6 +396,9 @@ const configSchema = {
}, },
type: 'object', type: 'object',
}, },
strictNextHead: {
type: 'boolean',
},
swcFileReading: { swcFileReading: {
type: 'boolean', type: 'boolean',
}, },
......
...@@ -114,6 +114,7 @@ export interface NextJsWebpackConfig { ...@@ -114,6 +114,7 @@ export interface NextJsWebpackConfig {
} }
export interface ExperimentalConfig { export interface ExperimentalConfig {
strictNextHead?: boolean
clientRouterFilter?: boolean clientRouterFilter?: boolean
clientRouterFilterRedirects?: boolean clientRouterFilterRedirects?: boolean
// decimal for percent for possible false positives // decimal for percent for possible false positives
......
...@@ -266,6 +266,7 @@ export type RenderOptsPartial = { ...@@ -266,6 +266,7 @@ export type RenderOptsPartial = {
images: ImageConfigComplete images: ImageConfigComplete
largePageDataBytes?: number largePageDataBytes?: number
isOnDemandRevalidate?: boolean isOnDemandRevalidate?: boolean
strictNextHead: boolean
} }
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
...@@ -1438,6 +1439,7 @@ export async function renderToHTML( ...@@ -1438,6 +1439,7 @@ export async function renderToHTML(
isPreview: isPreview === true ? true : undefined, isPreview: isPreview === true ? true : undefined,
notFoundSrcPage: notFoundSrcPage && dev ? notFoundSrcPage : undefined, notFoundSrcPage: notFoundSrcPage && dev ? notFoundSrcPage : undefined,
}, },
strictNextHead: renderOpts.strictNextHead,
buildManifest: filteredBuildManifest, buildManifest: filteredBuildManifest,
docComponentsRendered, docComponentsRendered,
dangerousAsPath: router.asPath, dangerousAsPath: router.asPath,
......
...@@ -8,6 +8,7 @@ import { createContext } from 'react' ...@@ -8,6 +8,7 @@ import { createContext } from 'react'
export type HtmlProps = { export type HtmlProps = {
__NEXT_DATA__: NEXT_DATA __NEXT_DATA__: NEXT_DATA
strictNextHead: boolean
dangerousAsPath: string dangerousAsPath: string
docComponentsRendered: { docComponentsRendered: {
Html?: boolean Html?: boolean
......
...@@ -14,6 +14,11 @@ describe('should set-up next', () => { ...@@ -14,6 +14,11 @@ describe('should set-up next', () => {
pages: new FileRef(join(__dirname, 'app/pages')), pages: new FileRef(join(__dirname, 'app/pages')),
components: new FileRef(join(__dirname, 'app/components')), components: new FileRef(join(__dirname, 'app/components')),
}, },
nextConfig: {
experimental: {
strictNextHead: true,
},
},
}) })
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
...@@ -27,7 +32,7 @@ describe('should set-up next', () => { ...@@ -27,7 +32,7 @@ describe('should set-up next', () => {
}) })
expect(html).toContain( expect(html).toContain(
`<meta charset="utf-8"><meta name="viewport" content="width=device-width"><meta name="test-head-1" content="hello">` `<meta charset="utf-8"><meta name="next-head" content="1"><meta name="viewport" content="width=device-width"><meta name="next-head" content="1"><meta name="test-head-1" content="hello">`
) )
}) })
......
...@@ -3,4 +3,7 @@ module.exports = { ...@@ -3,4 +3,7 @@ module.exports = {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60, maxInactiveAge: 1000 * 60 * 60,
}, },
experimental: {
strictNextHead: true,
},
} }
...@@ -97,12 +97,13 @@ export default function (render, fetch, ctx) { ...@@ -97,12 +97,13 @@ export default function (render, fetch, ctx) {
) )
expect(html).toContain('<meta content="my meta"/>') expect(html).toContain('<meta content="my meta"/>')
expect(html).toContain( expect(html).toContain(
'<link rel="stylesheet" href="/dup-style.css"/><link rel="stylesheet" href="/dup-style.css"/>' '<link rel="stylesheet" href="/dup-style.css"/><meta name="next-head" content="1"/><link rel="stylesheet" href="/dup-style.css"/>'
)
expect(html).toContain('<link rel="stylesheet" href="dedupe-style.css"/>')
expect(html).not.toContain(
'<link rel="stylesheet" href="dedupe-style.css"/><link rel="stylesheet" href="dedupe-style.css"/>'
) )
const dedupeLink = '<link rel="stylesheet" href="dedupe-style.css"/>'
expect(html).toContain(dedupeLink)
expect(
html.substring(html.indexOf(dedupeLink) + dedupeLink.length)
).not.toContain('<link rel="stylesheet" href="dedupe-style.css"/>')
expect(html).toContain( expect(html).toContain(
'<link rel="alternate" hrefLang="en" href="/last/en"/>' '<link rel="alternate" hrefLang="en" href="/last/en"/>'
) )
...@@ -195,13 +196,10 @@ export default function (render, fetch, ctx) { ...@@ -195,13 +196,10 @@ export default function (render, fetch, ctx) {
it('should place charset element at the top of <head>', async () => { it('should place charset element at the top of <head>', async () => {
const html = await render('/head-priority') const html = await render('/head-priority')
const nextHeadElement = const nextHeadElement =
'<meta charSet="iso-8859-5"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="title" content="head title"/>' '<meta charSet="iso-8859-5"/><meta name="next-head" content="1"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="next-head" content="1"/><meta name="title" content="head title"/>'
const nextHeadCountElement = '<meta name="next-head-count" content="3"/>'
const documentHeadElement = const documentHeadElement =
'<meta name="keywords" content="document head test"/>' '<meta name="keywords" content="document head test"/>'
expect(html).toContain( expect(html).toContain(`${nextHeadElement}${documentHeadElement}`)
`${nextHeadElement}${nextHeadCountElement}${documentHeadElement}`
)
}) })
it('should render the page with custom extension', async () => { it('should render the page with custom extension', async () => {
......
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