Unverified Commit f0bf674e authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Remove `experimental.strictNextHead` (#81882)

parent 186d169e
...@@ -254,8 +254,6 @@ export function getDefineEnv({ ...@@ -254,8 +254,6 @@ export function getDefineEnv({
config.experimental.scrollRestoration ?? false, config.experimental.scrollRestoration ?? false,
...getImageConfig(config, dev), ...getImageConfig(config, dev),
'process.env.__NEXT_ROUTER_BASEPATH': config.basePath, 'process.env.__NEXT_ROUTER_BASEPATH': config.basePath,
'process.env.__NEXT_STRICT_NEXT_HEAD':
config.experimental.strictNextHead ?? true,
'process.env.__NEXT_HAS_REWRITES': hasRewrites, 'process.env.__NEXT_HAS_REWRITES': hasRewrites,
'process.env.__NEXT_CONFIG_OUTPUT': config.output, 'process.env.__NEXT_CONFIG_OUTPUT': config.output,
'process.env.__NEXT_I18N_SUPPORT': !!config.i18n, 'process.env.__NEXT_I18N_SUPPORT': !!config.i18n,
......
...@@ -144,7 +144,6 @@ async function requestHandler( ...@@ -144,7 +144,6 @@ async function requestHandler(
ComponentMod: pageMod, ComponentMod: pageMod,
pageConfig: pageMod.pageConfig, pageConfig: pageMod.pageConfig,
routeModule: pageMod.routeModule, routeModule: pageMod.routeModule,
strictNextHead: nextConfig.experimental.strictNextHead ?? true,
canonicalBase: nextConfig.amp.canonicalBase || '', canonicalBase: nextConfig.amp.canonicalBase || '',
previewProps: prerenderManifest.preview, previewProps: prerenderManifest.preview,
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer, ampOptimizerConfig: nextConfig.experimental.amp?.optimizer,
......
...@@ -293,8 +293,6 @@ export async function handler( ...@@ -293,8 +293,6 @@ export async function handler(
reactLoadableManifest, reactLoadableManifest,
assetPrefix: nextConfig.assetPrefix, assetPrefix: nextConfig.assetPrefix,
strictNextHead:
nextConfig.experimental.strictNextHead ?? true,
previewProps: prerenderManifest.preview, previewProps: prerenderManifest.preview,
images: nextConfig.images as any, images: nextConfig.images as any,
nextConfigOutput: nextConfig.output, nextConfigOutput: nextConfig.output,
......
...@@ -50,104 +50,52 @@ export function isEqualNode(oldTag: Element, newTag: Element) { ...@@ -50,104 +50,52 @@ export function isEqualNode(oldTag: Element, newTag: Element) {
return oldTag.isEqualNode(newTag) return oldTag.isEqualNode(newTag)
} }
let updateElements: (type: string, components: JSX.Element[]) => void function updateElements(type: string, components: JSX.Element[]) {
const headEl = document.querySelector('head')
if (!headEl) return
if (process.env.__NEXT_STRICT_NEXT_HEAD) { const oldTags = new Set(headEl.querySelectorAll(`${type}[data-next-head]`))
updateElements = (type, components) => {
const headEl = document.querySelector('head')
if (!headEl) return
const oldTags = new Set(headEl.querySelectorAll(`${type}[data-next-head]`)) if (type === 'meta') {
const metaCharset = headEl.querySelector('meta[charset]')
if (type === 'meta') { if (metaCharset !== null) {
const metaCharset = headEl.querySelector('meta[charset]') oldTags.add(metaCharset)
if (metaCharset !== null) {
oldTags.add(metaCharset)
}
} }
}
const newTags: Element[] = [] const newTags: Element[] = []
for (let i = 0; i < components.length; i++) { for (let i = 0; i < components.length; i++) {
const component = components[i] const component = components[i]
const newTag = reactElementToDOM(component) const newTag = reactElementToDOM(component)
newTag.setAttribute('data-next-head', '') newTag.setAttribute('data-next-head', '')
let isNew = true
for (const oldTag of oldTags) {
if (isEqualNode(oldTag, newTag)) {
oldTags.delete(oldTag)
isNew = false
break
}
}
if (isNew) { let isNew = true
newTags.push(newTag) for (const oldTag of oldTags) {
if (isEqualNode(oldTag, newTag)) {
oldTags.delete(oldTag)
isNew = false
break
} }
} }
for (const oldTag of oldTags) { if (isNew) {
oldTag.parentNode?.removeChild(oldTag) newTags.push(newTag)
}
for (const newTag of newTags) {
// meta[charset] must be first element so special case
if (
newTag.tagName.toLowerCase() === 'meta' &&
newTag.getAttribute('charset') !== null
) {
headEl.prepend(newTag)
}
headEl.appendChild(newTag)
} }
} }
} else {
updateElements = (type, components) => {
const headEl = document.getElementsByTagName('head')[0]
const headCountEl: HTMLMetaElement = headEl.querySelector(
'meta[name=next-head-count]'
) as HTMLMetaElement
if (process.env.NODE_ENV !== 'production') {
if (!headCountEl) {
console.error(
'Warning: next-head-count is missing. https://nextjs.org/docs/messages/next-head-count-missing'
)
return
}
}
const headCount = Number(headCountEl.content) for (const oldTag of oldTags) {
const oldTags: Element[] = [] oldTag.parentNode?.removeChild(oldTag)
}
for ( for (const newTag of newTags) {
let i = 0, j = headCountEl.previousElementSibling; // meta[charset] must be first element so special case
i < headCount; if (
i++, j = j?.previousElementSibling || null newTag.tagName.toLowerCase() === 'meta' &&
newTag.getAttribute('charset') !== null
) { ) {
if (j?.tagName?.toLowerCase() === type) { headEl.prepend(newTag)
oldTags.push(j)
}
} }
const newTags = (components.map(reactElementToDOM) as HTMLElement[]).filter( headEl.appendChild(newTag)
(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) => t.parentNode?.removeChild(t))
newTags.forEach((t) => headEl.insertBefore(t, headCountEl))
headCountEl.content = (
headCount -
oldTags.length +
newTags.length
).toString()
} }
} }
......
...@@ -393,7 +393,6 @@ async function exportAppImpl( ...@@ -393,7 +393,6 @@ async function exportAppImpl(
serverActionsManifest, serverActionsManifest,
} }
: {}), : {}),
strictNextHead: nextConfig.experimental.strictNextHead ?? true,
deploymentId: nextConfig.deploymentId, deploymentId: nextConfig.deploymentId,
htmlLimitedBots: nextConfig.htmlLimitedBots.source, htmlLimitedBots: nextConfig.htmlLimitedBots.source,
experimental: { experimental: {
......
...@@ -657,22 +657,12 @@ export class Head extends React.Component<HeadProps> { ...@@ -657,22 +657,12 @@ export class Head extends React.Component<HeadProps> {
child.props['rel'] === 'preload' && child.props['rel'] === 'preload' &&
child.props['as'] === 'style' child.props['as'] === 'style'
) { ) {
if (this.context.strictNextHead) { cssPreloads.push(child)
cssPreloads.push(
React.cloneElement(child, { 'data-next-head': '' })
)
} else {
cssPreloads.push(child)
}
} else { } else {
if (child) { if (child) {
if (this.context.strictNextHead) { otherHeadElements.push(
otherHeadElements.push( React.cloneElement(child, { 'data-next-head': '' })
React.cloneElement(child, { 'data-next-head': '' }) )
)
} else {
otherHeadElements.push(child)
}
} }
} }
}) })
...@@ -811,12 +801,6 @@ export class Head extends React.Component<HeadProps> { ...@@ -811,12 +801,6 @@ export class Head extends React.Component<HeadProps> {
</> </>
)} )}
{head} {head}
{this.context.strictNextHead ? null : (
<meta
name="next-head-count"
content={React.Children.count(head || []).toString()}
/>
)}
{children} {children}
......
...@@ -565,7 +565,6 @@ export default abstract class Server< ...@@ -565,7 +565,6 @@ export default abstract class Server<
supportsDynamicResponse: true, supportsDynamicResponse: true,
trailingSlash: this.nextConfig.trailingSlash, trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.deploymentId, deploymentId: this.nextConfig.deploymentId,
strictNextHead: this.nextConfig.experimental.strictNextHead ?? true,
poweredByHeader: this.nextConfig.poweredByHeader, poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase || '', canonicalBase: this.nextConfig.amp.canonicalBase || '',
generateEtags, generateEtags,
......
...@@ -414,7 +414,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -414,7 +414,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
algorithm: z.enum(['sha256', 'sha384', 'sha512']).optional(), algorithm: z.enum(['sha256', 'sha384', 'sha512']).optional(),
}) })
.optional(), .optional(),
strictNextHead: z.boolean().optional(),
swcPlugins: z swcPlugins: z
// The specific swc plugin's option is unknown, use z.any() here // The specific swc plugin's option is unknown, use z.any() here
.array(z.tuple([z.string(), z.record(z.string(), z.any())])) .array(z.tuple([z.string(), z.record(z.string(), z.any())]))
......
...@@ -335,8 +335,6 @@ export interface ExperimentalConfig { ...@@ -335,8 +335,6 @@ export interface ExperimentalConfig {
dynamicOnHover?: boolean dynamicOnHover?: boolean
appDocumentPreloading?: boolean appDocumentPreloading?: boolean
preloadEntriesOnStart?: boolean preloadEntriesOnStart?: boolean
/** @default true */
strictNextHead?: boolean
clientRouterFilter?: boolean clientRouterFilter?: boolean
clientRouterFilterRedirects?: boolean clientRouterFilterRedirects?: boolean
/** /**
...@@ -1472,7 +1470,6 @@ export const defaultConfig = Object.freeze({ ...@@ -1472,7 +1470,6 @@ export const defaultConfig = Object.freeze({
devtoolSegmentExplorer: true, devtoolSegmentExplorer: true,
browserDebugInfoInTerminal: false, browserDebugInfoInTerminal: false,
optimizeRouterScrolling: false, optimizeRouterScrolling: false,
strictNextHead: true,
}, },
htmlLimitedBots: undefined, htmlLimitedBots: undefined,
bundlePagesRouterDependencies: false, bundlePagesRouterDependencies: false,
......
...@@ -287,7 +287,6 @@ export type RenderOptsPartial = { ...@@ -287,7 +287,6 @@ export type RenderOptsPartial = {
images: ImageConfigComplete images: ImageConfigComplete
largePageDataBytes?: number largePageDataBytes?: number
isOnDemandRevalidate?: boolean isOnDemandRevalidate?: boolean
strictNextHead: boolean
isPossibleServerAction?: boolean isPossibleServerAction?: boolean
isExperimentalCompile?: boolean isExperimentalCompile?: boolean
isPrefetch?: boolean isPrefetch?: boolean
...@@ -1524,7 +1523,6 @@ export async function renderToHTMLImpl( ...@@ -1524,7 +1523,6 @@ export async function renderToHTMLImpl(
notFoundSrcPage: notFoundSrcPage && dev ? notFoundSrcPage : undefined, notFoundSrcPage: notFoundSrcPage && dev ? notFoundSrcPage : undefined,
}, },
nonce, nonce,
strictNextHead: renderOpts.strictNextHead,
buildManifest: filteredBuildManifest, buildManifest: filteredBuildManifest,
docComponentsRendered, docComponentsRendered,
dangerousAsPath: router.asPath, dangerousAsPath: router.asPath,
......
...@@ -9,7 +9,6 @@ import { createContext, useContext, type JSX } from 'react' ...@@ -9,7 +9,6 @@ import { createContext, useContext, type JSX } from 'react'
export type HtmlProps = { export type HtmlProps = {
__NEXT_DATA__: NEXT_DATA __NEXT_DATA__: NEXT_DATA
nonce?: string nonce?: string
strictNextHead: boolean
dangerousAsPath: string dangerousAsPath: string
docComponentsRendered: { docComponentsRendered: {
Html?: boolean Html?: boolean
......
...@@ -4,12 +4,6 @@ module.exports = { ...@@ -4,12 +4,6 @@ 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:
process.env.TEST_STRICT_NEXT_HEAD !== undefined
? {
strictNextHead: process.env.TEST_STRICT_NEXT_HEAD === 'true',
}
: {},
// scroll position can be finicky with the // scroll position can be finicky with the
// indicators showing so hide by default // indicators showing so hide by default
devIndicators: false, devIndicators: false,
......
...@@ -4,202 +4,174 @@ import { waitFor } from 'next-test-utils' ...@@ -4,202 +4,174 @@ import { waitFor } from 'next-test-utils'
import path from 'path' import path from 'path'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18 describe('updating <Head /> while client routing', () => {
const { next } = nextTestSetup({
describe.each([[false], [true]])( files: path.join(__dirname, 'fixture'),
'updating <Head /> with strictNextHead=%s while client routing', })
(strictNextHead) => {
const { next } = nextTestSetup({ it.each([true, false])(
files: path.join(__dirname, 'fixture'), 'should handle boolean async prop in next/head client-side: %s',
env: { async (bool) => {
TEST_STRICT_NEXT_HEAD: String(strictNextHead), const browser = await next.browser('/head')
}, const value = await browser.eval(
}) `document.querySelector('script[src="/test-async-${JSON.stringify(
bool
)}.js"]').async`
)
it.each([true, false])( expect(value).toBe(bool)
'should handle boolean async prop in next/head client-side: %s', }
async (bool) => { )
const browser = await next.browser('/head')
const value = await browser.eval(
`document.querySelector('script[src="/test-async-${JSON.stringify(
bool
)}.js"]').async`
)
expect(value).toBe(bool)
}
)
it('should only execute async and defer scripts once', async () => { it('should only execute async and defer scripts once', async () => {
const browser = await next.browser('/head') const browser = await next.browser('/head')
await browser.waitForElementByCss('h1') await browser.waitForElementByCss('h1')
await waitFor(2000) await waitFor(2000)
expect(Number(await browser.eval('window.__test_async_executions'))).toBe( expect(Number(await browser.eval('window.__test_async_executions'))).toBe(1)
strictNextHead || isReact18 expect(Number(await browser.eval('window.__test_defer_executions'))).toBe(1)
? 1
: // <meta name="next-head-count" /> is floated before <script />.
// head-manager thinks it needs to add these again resulting in another execution.
2
)
expect(Number(await browser.eval('window.__test_defer_executions'))).toBe(
strictNextHead || isReact18
? 1
: // <meta name="next-head-count" /> is floated before <script defer />.
// head-manager thinks it needs to add these again resulting in another execution.
2
)
await browser.elementByCss('#reverseScriptOrder').click() await browser.elementByCss('#reverseScriptOrder').click()
await waitFor(2000) await waitFor(2000)
expect(Number(await browser.eval('window.__test_async_executions'))).toBe( expect(Number(await browser.eval('window.__test_async_executions'))).toBe(1)
strictNextHead || isReact18 ? 1 : 2 expect(Number(await browser.eval('window.__test_defer_executions'))).toBe(1)
)
expect(Number(await browser.eval('window.__test_defer_executions'))).toBe(
strictNextHead || isReact18 ? 1 : 2
)
await browser.elementByCss('#toggleScript').click() await browser.elementByCss('#toggleScript').click()
await waitFor(2000) await waitFor(2000)
expect(Number(await browser.eval('window.__test_async_executions'))).toBe( expect(Number(await browser.eval('window.__test_async_executions'))).toBe(1)
strictNextHead || isReact18 ? 1 : 2 expect(Number(await browser.eval('window.__test_defer_executions'))).toBe(1)
) })
expect(Number(await browser.eval('window.__test_defer_executions'))).toBe(
strictNextHead || isReact18 ? 1 : 2
)
})
it('should warn when stylesheets or scripts are in head', async () => { it('should warn when stylesheets or scripts are in head', async () => {
const browser = await next.browser('/head') const browser = await next.browser('/head')
await browser.waitForElementByCss('h1') await browser.waitForElementByCss('h1')
await waitFor(1000) await waitFor(1000)
const browserLogs = await browser.log() const browserLogs = await browser.log()
let foundStyles = false let foundStyles = false
let foundScripts = false let foundScripts = false
const logs = [] const logs = []
browserLogs.forEach(({ message }) => { browserLogs.forEach(({ message }) => {
if (message.includes('Do not add stylesheets using next/head')) { if (message.includes('Do not add stylesheets using next/head')) {
foundStyles = true foundStyles = true
logs.push(message) logs.push(message)
} }
if (message.includes('Do not add <script> tags using next/head')) { if (message.includes('Do not add <script> tags using next/head')) {
foundScripts = true foundScripts = true
logs.push(message) logs.push(message)
} }
})
expect(foundStyles).toEqual(true)
expect(foundScripts).toEqual(true)
// Warnings are unique
expect(logs.length).toEqual(new Set(logs).size)
}) })
it('should warn when scripts are in head', async () => { expect(foundStyles).toEqual(true)
const browser = await next.browser('/head') expect(foundScripts).toEqual(true)
await browser.waitForElementByCss('h1')
await waitFor(1000) // Warnings are unique
const browserLogs = await browser.log() expect(logs.length).toEqual(new Set(logs).size)
let found = false })
browserLogs.forEach((log) => {
if (log.message.includes('Use next/script instead')) { it('should warn when scripts are in head', async () => {
found = true const browser = await next.browser('/head')
} await browser.waitForElementByCss('h1')
}) await waitFor(1000)
expect(found).toEqual(true) const browserLogs = await browser.log()
let found = false
browserLogs.forEach((log) => {
if (log.message.includes('Use next/script instead')) {
found = true
}
}) })
expect(found).toEqual(true)
it('should not warn when application/ld+json scripts are in head', async () => { })
const browser = await next.browser('/head-with-json-ld-snippet')
await browser.waitForElementByCss('h1') it('should not warn when application/ld+json scripts are in head', async () => {
await waitFor(1000) const browser = await next.browser('/head-with-json-ld-snippet')
const browserLogs = await browser.log() await browser.waitForElementByCss('h1')
let found = false await waitFor(1000)
browserLogs.forEach((log) => { const browserLogs = await browser.log()
if (log.message.includes('Use next/script instead')) { let found = false
found = true browserLogs.forEach((log) => {
} if (log.message.includes('Use next/script instead')) {
}) found = true
expect(found).toEqual(false) }
}) })
expect(found).toEqual(false)
})
it('should update head during client routing', async () => { it('should update head during client routing', async () => {
const browser = await next.browser('/nav/head-1') const browser = await next.browser('/nav/head-1')
expect( expect(
await browser
.elementByCss('meta[name="description"]')
.getAttribute('content')
).toBe('Head One')
await browser await browser
.elementByCss('#to-head-2') .elementByCss('meta[name="description"]')
.click() .getAttribute('content')
.waitForElementByCss('#head-2', 3000) ).toBe('Head One')
expect(
await browser await browser
.elementByCss('meta[name="description"]') .elementByCss('#to-head-2')
.getAttribute('content') .click()
).toBe('Head Two') .waitForElementByCss('#head-2', 3000)
expect(
await browser await browser
.elementByCss('#to-head-1') .elementByCss('meta[name="description"]')
.click() .getAttribute('content')
.waitForElementByCss('#head-1', 3000) ).toBe('Head Two')
expect(
await browser await browser
.elementByCss('meta[name="description"]') .elementByCss('#to-head-1')
.getAttribute('content') .click()
).toBe('Head One') .waitForElementByCss('#head-1', 3000)
expect(
await browser await browser
.elementByCss('#to-head-3') .elementByCss('meta[name="description"]')
.click() .getAttribute('content')
.waitForElementByCss('#head-3', 3000) ).toBe('Head One')
expect(
await browser await browser
.elementByCss('meta[name="description"]') .elementByCss('#to-head-3')
.getAttribute('content') .click()
).toBe('Head Three') .waitForElementByCss('#head-3', 3000)
expect(await browser.eval('document.title')).toBe('') expect(
await browser await browser
.elementByCss('#to-head-1') .elementByCss('meta[name="description"]')
.click() .getAttribute('content')
.waitForElementByCss('#head-1', 3000) ).toBe('Head Three')
expect( expect(await browser.eval('document.title')).toBe('')
await browser
.elementByCss('meta[name="description"]') await browser
.getAttribute('content') .elementByCss('#to-head-1')
).toBe('Head One') .click()
}) .waitForElementByCss('#head-1', 3000)
expect(
it('should update title during client routing', async () => {
const browser = await next.browser('/nav/head-1')
expect(await browser.eval('document.title')).toBe('this is head-1')
await browser
.elementByCss('#to-head-2')
.click()
.waitForElementByCss('#head-2', 3000)
expect(await browser.eval('document.title')).toBe('this is head-2')
await browser await browser
.elementByCss('#to-head-1') .elementByCss('meta[name="description"]')
.click() .getAttribute('content')
.waitForElementByCss('#head-1', 3000) ).toBe('Head One')
expect(await browser.eval('document.title')).toBe('this is head-1') })
})
it('should update title during client routing', async () => {
it('should update head when unmounting component', async () => { const browser = await next.browser('/nav/head-1')
const browser = await next.browser('/head-dynamic') expect(await browser.eval('document.title')).toBe('this is head-1')
expect(await browser.eval('document.title')).toBe('B')
await browser.elementByCss('button').click() await browser
expect(await browser.eval('document.title')).toBe('A') .elementByCss('#to-head-2')
await browser.elementByCss('button').click() .click()
expect(await browser.eval('document.title')).toBe('B') .waitForElementByCss('#head-2', 3000)
}) expect(await browser.eval('document.title')).toBe('this is head-2')
}
) await browser
.elementByCss('#to-head-1')
.click()
.waitForElementByCss('#head-1', 3000)
expect(await browser.eval('document.title')).toBe('this is head-1')
})
it('should update head when unmounting component', async () => {
const browser = await next.browser('/head-dynamic')
expect(await browser.eval('document.title')).toBe('B')
await browser.elementByCss('button').click()
expect(await browser.eval('document.title')).toBe('A')
await browser.elementByCss('button').click()
expect(await browser.eval('document.title')).toBe('B')
})
})
...@@ -8,336 +8,225 @@ import path from 'path' ...@@ -8,336 +8,225 @@ import path from 'path'
const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18 const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
describe('Client Navigation rendering <Head />', () => { describe('Client Navigation rendering <Head />', () => {
describe.each([[false], [true], [undefined]])( const { next } = nextTestSetup({
'with strictNextHead=%s', files: path.join(__dirname, 'fixture'),
(strictNextHead) => { })
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixture'), function render(
env: pathname: Parameters<typeof renderViaHTTP>[1],
strictNextHead !== undefined query?: Parameters<typeof renderViaHTTP>[2]
? { ) {
TEST_STRICT_NEXT_HEAD: String(strictNextHead), return renderViaHTTP(next.appPort, pathname, query)
} }
: {},
}) it('should handle undefined prop in head server-side', async () => {
const html = await render('/head')
function render( const $ = cheerio.load(html)
pathname: Parameters<typeof renderViaHTTP>[1], const value = 'content' in $('meta[name="empty-content"]').attr()
query?: Parameters<typeof renderViaHTTP>[2]
) { expect(value).toBe(false)
return renderViaHTTP(next.appPort, pathname, query) })
}
// default-head contains an empty <Head />.
it('should handle undefined prop in head server-side', async () => { test('header renders default charset', async () => {
const html = await render('/head') const html = await render('/default-head')
const $ = cheerio.load(html) expect(html).toContain('<meta charSet="utf-8" data-next-head=""/>')
const value = 'content' in $('meta[name="empty-content"]').attr() expect(html).toContain('next-head, but only once.')
})
expect(value).toBe(false)
}) test('header renders default viewport', async () => {
const html = await render('/default-head')
// default-head contains an empty <Head />. expect(html).toContain(
test('header renders default charset', async () => { '<meta name="viewport" content="width=device-width" data-next-head=""/>'
const html = await render('/default-head') )
expect(html).toContain( })
strictNextHead !== false
? '<meta charSet="utf-8" data-next-head=""/>' test('header helper renders header information', async () => {
: '<meta charSet="utf-8"/>' const html = await render('/head')
) expect(html).toContain('<meta charSet="iso-8859-5" data-next-head=""/>')
expect(html).toContain('next-head, but only once.') expect(html).toContain('<meta content="my meta" data-next-head=""/>')
}) expect(html).toContain(
'<meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/>'
test('header renders default viewport', async () => { )
const html = await render('/default-head') expect(html).toContain('I can have meta tags')
expect(html).toContain( })
strictNextHead !== false
? '<meta name="viewport" content="width=device-width" data-next-head=""/>' test('header helper dedupes tags', async () => {
: '<meta name="viewport" content="width=device-width"/>' const html = await render('/head')
) expect(html).toContain('<meta charSet="iso-8859-5" data-next-head=""/>')
}) expect(html).not.toContain('<meta charSet="utf-8" data-next-head=""/>')
expect(html).toContain(
test('header helper renders header information', async () => { '<meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/>'
const html = await render('/head') )
expect(html).toContain( // Should contain only one viewport
strictNextHead !== false expect(html.match(/<meta name="viewport" /g).length).toBe(1)
? '<meta charSet="iso-8859-5" data-next-head=""/>' expect(html).not.toContain(
: '<meta charSet="iso-8859-5"/>' '<meta name="viewport" content="width=device-width"'
) )
expect(html).toContain( expect(html).toContain('<meta content="my meta" data-next-head=""/>')
strictNextHead !== false expect(html).toContain(
? '<meta content="my meta" data-next-head=""/>' '<link rel="stylesheet" href="/dup-style.css" data-next-head=""/><link rel="stylesheet" href="/dup-style.css" data-next-head=""/>'
: '<meta content="my meta"/>' )
) const dedupeLink =
expect(html).toContain( '<link rel="stylesheet" href="dedupe-style.css" data-next-head=""/>'
strictNextHead !== false expect(html).toContain(dedupeLink)
? '<meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/>' expect(
: '<meta name="viewport" content="width=device-width,initial-scale=1"/>' html.substring(html.indexOf(dedupeLink) + dedupeLink.length)
) ).not.toContain('<link rel="stylesheet" href="dedupe-style.css"')
expect(html).toContain('I can have meta tags') expect(html).toContain(
}) '<link rel="alternate" hrefLang="en" href="/last/en" data-next-head=""/>'
)
test('header helper dedupes tags', async () => { expect(html).not.toContain(
const html = await render('/head') '<link rel="alternate" hrefLang="en" href="/first/en"'
expect(html).toContain( )
strictNextHead !== false })
? '<meta charSet="iso-8859-5" data-next-head=""/>'
: '<meta charSet="iso-8859-5"/>' test('header helper dedupes tags with the same key as the default', async () => {
) const html = await render('/head-duplicate-default-keys')
expect(html).not.toContain( // Expect exactly one `charSet`
strictNextHead !== false expect((html.match(/charSet=/g) || []).length).toBe(1)
? '<meta charSet="utf-8" data-next-head=""/>' // Expect exactly one `viewport`
: '<meta charSet="utf-8"/>' expect((html.match(/name="viewport"/g) || []).length).toBe(1)
) expect(html).toContain('<meta charSet="iso-8859-1" data-next-head=""/>')
expect(html).toContain( expect(html).toContain(
strictNextHead !== false '<meta name="viewport" content="width=500" data-next-head=""/>'
? '<meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/>' )
: '<meta name="viewport" content="width=device-width,initial-scale=1"/>' })
)
// Should contain only one viewport test('header helper avoids dedupe of specific tags', async () => {
expect(html.match(/<meta name="viewport" /g).length).toBe(1) const html = await render('/head')
expect(html).not.toContain( console.log(html)
'<meta name="viewport" content="width=device-width"' expect(html).toContain(
) '<meta property="article:tag" content="tag1" data-next-head=""/>'
expect(html).toContain( )
strictNextHead !== false expect(html).toContain(
? '<meta content="my meta" data-next-head=""/>' '<meta property="article:tag" content="tag2" data-next-head=""/>'
: '<meta content="my meta"/>' )
) expect(html).not.toContain('<meta property="dedupe:tag" content="tag3"')
expect(html).toContain( expect(html).toContain(
strictNextHead !== false '<meta property="dedupe:tag" content="tag4" data-next-head=""/>'
? '<link rel="stylesheet" href="/dup-style.css" data-next-head=""/><link rel="stylesheet" href="/dup-style.css" data-next-head=""/>' )
: '<link rel="stylesheet" href="/dup-style.css"/><link rel="stylesheet" href="/dup-style.css"/>' expect(html).toContain(
) '<meta property="og:image" content="ogImageTag1" data-next-head=""/>'
const dedupeLink = )
strictNextHead !== false expect(html).toContain(
? '<link rel="stylesheet" href="dedupe-style.css" data-next-head=""/>' '<meta property="og:image" content="ogImageTag2" data-next-head=""/>'
: '<link rel="stylesheet" href="dedupe-style.css"/>' )
expect(html).toContain(dedupeLink) expect(html).toContain(
expect( '<meta property="og:image:alt" content="ogImageAltTag1" data-next-head=""/>'
html.substring(html.indexOf(dedupeLink) + dedupeLink.length) )
).not.toContain('<link rel="stylesheet" href="dedupe-style.css"') expect(html).toContain(
expect(html).toContain( '<meta property="og:image:alt" content="ogImageAltTag2" data-next-head=""/>'
strictNextHead !== false )
? '<link rel="alternate" hrefLang="en" href="/last/en" data-next-head=""/>' expect(html).toContain(
: '<link rel="alternate" hrefLang="en" href="/last/en"/>' '<meta property="og:image:width" content="ogImageWidthTag1" data-next-head=""/>'
) )
expect(html).not.toContain( expect(html).toContain(
'<link rel="alternate" hrefLang="en" href="/first/en"' '<meta property="og:image:width" content="ogImageWidthTag2" data-next-head=""/>'
) )
}) expect(html).toContain(
'<meta property="og:image:height" content="ogImageHeightTag1" data-next-head=""/>'
test('header helper dedupes tags with the same key as the default', async () => { )
const html = await render('/head-duplicate-default-keys') expect(html).toContain(
// Expect exactly one `charSet` '<meta property="og:image:height" content="ogImageHeightTag2" data-next-head=""/>'
expect((html.match(/charSet=/g) || []).length).toBe(1) )
// Expect exactly one `viewport` expect(html).toContain(
expect((html.match(/name="viewport"/g) || []).length).toBe(1) '<meta property="og:image:type" content="ogImageTypeTag1" data-next-head=""/>'
expect(html).toContain( )
strictNextHead !== false expect(html).toContain(
? '<meta charSet="iso-8859-1" data-next-head=""/>' '<meta property="og:image:type" content="ogImageTypeTag2" data-next-head=""/>'
: '<meta charSet="iso-8859-1"/>' )
) expect(html).toContain(
expect(html).toContain( '<meta property="og:image:secure_url" content="ogImageSecureUrlTag1" data-next-head=""/>'
strictNextHead !== false )
? '<meta name="viewport" content="width=500" data-next-head=""/>' expect(html).toContain(
: '<meta name="viewport" content="width=500"/>' '<meta property="og:image:secure_url" content="ogImageSecureUrlTag2" data-next-head=""/>'
) )
}) expect(html).toContain(
'<meta property="og:image:url" content="ogImageUrlTag1" data-next-head=""/>'
test('header helper avoids dedupe of specific tags', async () => { )
const html = await render('/head') expect(html).toContain(
console.log(html) '<meta property="og:image:url" content="ogImageUrlTag2" data-next-head=""/>'
expect(html).toContain( )
strictNextHead !== false expect(html).toContain(
? '<meta property="article:tag" content="tag1" data-next-head=""/>' '<meta property="fb:pages" content="fbpages1" data-next-head=""/>'
: '<meta property="article:tag" content="tag1"/>' )
) expect(html).toContain(
expect(html).toContain( '<meta property="fb:pages" content="fbpages2" data-next-head=""/>'
strictNextHead !== false )
? '<meta property="article:tag" content="tag2" data-next-head=""/>' })
: '<meta property="article:tag" content="tag2"/>'
) test('header helper avoids dedupe of meta tags with the same name if they use unique keys', async () => {
expect(html).not.toContain('<meta property="dedupe:tag" content="tag3"') const html = await render('/head')
expect(html).toContain( expect(html).toContain(
strictNextHead !== false '<meta name="citation_author" content="authorName1" data-next-head=""/>'
? '<meta property="dedupe:tag" content="tag4" data-next-head=""/>' )
: '<meta property="dedupe:tag" content="tag4"/>' expect(html).toContain(
) '<meta name="citation_author" content="authorName2" data-next-head=""/>'
expect(html).toContain( )
strictNextHead !== false })
? '<meta property="og:image" content="ogImageTag1" data-next-head=""/>'
: '<meta property="og:image" content="ogImageTag1"/>' test('header helper renders Fragment children', async () => {
) const html = await render('/head')
expect(html).toContain( expect(html).toContain('<title data-next-head="">Fragment title</title>')
strictNextHead !== false expect(html).toContain('<meta content="meta fragment" data-next-head=""/>')
? '<meta property="og:image" content="ogImageTag2" data-next-head=""/>' })
: '<meta property="og:image" content="ogImageTag2"/>'
) test('header helper renders boolean attributes correctly children', async () => {
expect(html).toContain( const html = await render('/head')
strictNextHead !== false expect(html).toContain(
? '<meta property="og:image:alt" content="ogImageAltTag1" data-next-head=""/>' '<script src="/test-async-false.js" data-next-head="">'
: '<meta property="og:image:alt" content="ogImageAltTag1"/>' )
) expect(html).toContain(
expect(html).toContain( '<script src="/test-async-true.js" async="" data-next-head="">'
strictNextHead !== false )
? '<meta property="og:image:alt" content="ogImageAltTag2" data-next-head=""/>' expect(html).toContain(
: '<meta property="og:image:alt" content="ogImageAltTag2"/>' '<script src="/test-defer.js" defer="" data-next-head="">'
) )
expect(html).toContain( })
strictNextHead !== false
? '<meta property="og:image:width" content="ogImageWidthTag1" data-next-head=""/>' it('should place charset element at the top of <head>', async () => {
: '<meta property="og:image:width" content="ogImageWidthTag1"/>' const html = await render('/head-priority')
) const nextHeadElement =
expect(html).toContain( '<meta charSet="iso-8859-5" data-next-head=""/><meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/><meta name="title" content="head title" data-next-head=""/>'
strictNextHead !== false const documentHeadElement =
? '<meta property="og:image:width" content="ogImageWidthTag2" data-next-head=""/>' '<meta name="keywords" content="document head test"/>'
: '<meta property="og:image:width" content="ogImageWidthTag2"/>'
) expect(html).toContain(
expect(html).toContain( isReact18
strictNextHead !== false ? // charset is not actually at the top.
? '<meta property="og:image:height" content="ogImageHeightTag1" data-next-head=""/>' // data-next-hide-fouc comes first
: '<meta property="og:image:height" content="ogImageHeightTag1"/>' `</style></noscript>${nextHeadElement}${documentHeadElement}`
) : `<head>${nextHeadElement}${documentHeadElement}`
expect(html).toContain( )
strictNextHead !== false })
? '<meta property="og:image:height" content="ogImageHeightTag2" data-next-head=""/>'
: '<meta property="og:image:height" content="ogImageHeightTag2"/>' test('custom meta properties are rendered only once', async () => {
) const browser = await next.browser('/head-with-custom-metadata')
expect(html).toContain(
strictNextHead !== false // Check that title appears only once
? '<meta property="og:image:type" content="ogImageTypeTag1" data-next-head=""/>' const titleElements = await browser.elementsByCss('title')
: '<meta property="og:image:type" content="ogImageTypeTag1"/>' expect(titleElements).toHaveLength(1)
) const titleText = await browser.elementByCss('title').text()
expect(html).toContain( expect(titleText).toBe('Title Page')
strictNextHead !== false
? '<meta property="og:image:type" content="ogImageTypeTag2" data-next-head=""/>' // Check that each meta property appears only once
: '<meta property="og:image:type" content="ogImageTypeTag2"/>' const ogTitleElements = await browser.elementsByCss(
) 'meta[property="og:title"]'
expect(html).toContain( )
strictNextHead !== false expect(ogTitleElements).toHaveLength(1)
? '<meta property="og:image:secure_url" content="ogImageSecureUrlTag1" data-next-head=""/>' const ogTitleContent = await browser
: '<meta property="og:image:secure_url" content="ogImageSecureUrlTag1"/>' .elementByCss('meta[property="og:title"]')
) .getAttribute('content')
expect(html).toContain( expect(ogTitleContent).toBe('Title Content')
strictNextHead !== false
? '<meta property="og:image:secure_url" content="ogImageSecureUrlTag2" data-next-head=""/>' const descriptionElements = await browser.elementsByCss(
: '<meta property="og:image:secure_url" content="ogImageSecureUrlTag2"/>' 'meta[name="description"]'
) )
expect(html).toContain( expect(descriptionElements).toHaveLength(1)
strictNextHead !== false const descriptionContent = await browser
? '<meta property="og:image:url" content="ogImageUrlTag1" data-next-head=""/>' .elementByCss('meta[name="description"]')
: '<meta property="og:image:url" content="ogImageUrlTag1"/>' .getAttribute('content')
) expect(descriptionContent).toBe('Description Content')
expect(html).toContain( })
strictNextHead !== false
? '<meta property="og:image:url" content="ogImageUrlTag2" data-next-head=""/>'
: '<meta property="og:image:url" content="ogImageUrlTag2"/>'
)
expect(html).toContain(
strictNextHead !== false
? '<meta property="fb:pages" content="fbpages1" data-next-head=""/>'
: '<meta property="fb:pages" content="fbpages1"/>'
)
expect(html).toContain(
strictNextHead !== false
? '<meta property="fb:pages" content="fbpages2" data-next-head=""/>'
: '<meta property="fb:pages" content="fbpages2"/>'
)
})
test('header helper avoids dedupe of meta tags with the same name if they use unique keys', async () => {
const html = await render('/head')
expect(html).toContain(
strictNextHead !== false
? '<meta name="citation_author" content="authorName1" data-next-head=""/>'
: '<meta name="citation_author" content="authorName1"/>'
)
expect(html).toContain(
strictNextHead !== false
? '<meta name="citation_author" content="authorName2" data-next-head=""/>'
: '<meta name="citation_author" content="authorName2"/>'
)
})
test('header helper renders Fragment children', async () => {
const html = await render('/head')
expect(html).toContain(
strictNextHead !== false
? '<title data-next-head="">Fragment title</title>'
: '<title>Fragment title</title>'
)
expect(html).toContain(
strictNextHead !== false
? '<meta content="meta fragment" data-next-head=""/>'
: '<meta content="meta fragment"/>'
)
})
test('header helper renders boolean attributes correctly children', async () => {
const html = await render('/head')
expect(html).toContain(
strictNextHead !== false
? '<script src="/test-async-false.js" data-next-head="">'
: '<script src="/test-async-false.js">'
)
expect(html).toContain(
strictNextHead !== false
? '<script src="/test-async-true.js" async="" data-next-head="">'
: ''
)
expect(html).toContain(
strictNextHead !== false
? '<script src="/test-defer.js" defer="" data-next-head="">'
: ''
)
})
it('should place charset element at the top of <head>', async () => {
const html = await render('/head-priority')
const nextHeadElement =
strictNextHead !== false
? '<meta charSet="iso-8859-5" data-next-head=""/><meta name="viewport" content="width=device-width,initial-scale=1" data-next-head=""/><meta name="title" content="head title" data-next-head=""/>'
: '<meta charSet="iso-8859-5"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="title" content="head title"/><meta name="next-head-count" content="3"/>'
const documentHeadElement =
'<meta name="keywords" content="document head test"/>'
expect(html).toContain(
isReact18
? // charset is not actually at the top.
// data-next-hide-fouc comes first
`</style></noscript>${nextHeadElement}${documentHeadElement}`
: `<head>${nextHeadElement}${documentHeadElement}`
)
})
test('custom meta properties are rendered only once', async () => {
const browser = await next.browser('/head-with-custom-metadata')
// Check that title appears only once
const titleElements = await browser.elementsByCss('title')
expect(titleElements).toHaveLength(1)
const titleText = await browser.elementByCss('title').text()
expect(titleText).toBe('Title Page')
// Check that each meta property appears only once
const ogTitleElements = await browser.elementsByCss(
'meta[property="og:title"]'
)
expect(ogTitleElements).toHaveLength(1)
const ogTitleContent = await browser
.elementByCss('meta[property="og:title"]')
.getAttribute('content')
expect(ogTitleContent).toBe('Title Content')
const descriptionElements = await browser.elementsByCss(
'meta[name="description"]'
)
expect(descriptionElements).toHaveLength(1)
const descriptionContent = await browser
.elementByCss('meta[name="description"]')
.getAttribute('content')
expect(descriptionContent).toBe('Description Content')
})
}
)
}) })
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