Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Warn when <Head> contains invalid elements #21080

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/next/pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,14 @@ export class Head extends Component<
let children = this.props.children
// show a warning if Head contains <title> (only in development)
if (process.env.NODE_ENV !== 'production') {
const allowedHeadChildren = new Set([
'base',
'link',
'style',
'script',
'noscript',
'template',
])
children = React.Children.map(children, (child: any) => {
const isReactHelmet = child?.props?.['data-react-helmet']
if (!isReactHelmet) {
Expand All @@ -382,6 +390,10 @@ export class Head extends Component<
console.warn(
"Warning: viewport meta tags should not be used in _document.js's <Head>. https://err.sh/next.js/no-document-viewport-meta"
)
} else if (!allowedHeadChildren.has(child?.type)) {
console.warn(
`Warning: elements of type ${child?.type} should not be used in _document.js's <Head>.`
)
}
}
return child
Expand Down
1 change: 1 addition & 0 deletions test/integration/document-head-warnings/pages/_document.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class MyDocument extends Document {
<Head crossOrigin="anonymous">
<title>Check out this title!</title>
<meta name="viewport" content="viewport-fit=cover" />
<svg></svg>
</Head>
<body>
<Main />
Expand Down
6 changes: 6 additions & 0 deletions test/integration/document-head-warnings/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,11 @@ describe('Custom Document Head Warnings', () => {
/.*Warning: `Head` attribute `crossOrigin` is deprecated\..*/
)
})

it('warns when using an invalid tag in document/head', () => {
expect(output).toMatch(
/.*Warning: elements of type svg should not be used in _document.js's <Head>\..*/
)
})
})
})