Commit f8dfe026 authored by Luc's avatar Luc Committed by Tim Neutkens

Show warning if there is a title in _document.js's Head (#5160)

* show warning if there is a title in _document.js Head

* dont loop through children in production

* only 1 loop through this.props.children 💪

* also raise warning in test env

* check for null childs
parent ad93ff4b
# `<title>` should not be used in _document.js's `<Head>`
#### Why This Error Occurred
Adding `<title>` in `pages/_document.js` will lead to unexpected results with `next/head` since `_document.js` is only rendered on the initial pre-render.
#### Possible Ways to Fix It
Set `<title>` in `pages/_app.js` instead :
```js
// pages/_app.js
import App, {Container} from 'next/app'
import Head from 'next/head'
import React from 'react'
export default class MyApp extends App {
static async getInitialProps ({ Component, router, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return {pageProps}
}
render () {
const {Component, pageProps} = this.props
return <Container>
<Head>
<title>My new cool app</title>
</Head>
<Component {...pageProps} />
</Container>
}
}
```
### Useful Links
- [The issue this was reported in: #4596](https://github.com/zeit/next.js/issues/4596)
...@@ -104,6 +104,17 @@ export class Head extends Component { ...@@ -104,6 +104,17 @@ export class Head extends Component {
const { page, pathname, buildId } = __NEXT_DATA__ const { page, pathname, buildId } = __NEXT_DATA__
const pagePathname = getPagePathname(pathname) const pagePathname = getPagePathname(pathname)
let children = this.props.children
// show a warning if Head contains <title> (only in development)
if (process.env.NODE_ENV !== 'production') {
children = React.Children.map(children, (child) => {
if (child && child.type === 'title') {
console.warn("Warning: <title> should not be used in _document.js's <Head>. https://err.sh/next.js/no-document-title")
}
return child
})
}
return <head {...this.props}> return <head {...this.props}>
{(head || []).map((h, i) => React.cloneElement(h, { key: h.key || i }))} {(head || []).map((h, i) => React.cloneElement(h, { key: h.key || i }))}
{page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}`} as='script' nonce={this.props.nonce} />} {page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}`} as='script' nonce={this.props.nonce} />}
...@@ -113,7 +124,7 @@ export class Head extends Component { ...@@ -113,7 +124,7 @@ export class Head extends Component {
{this.getPreloadMainLinks()} {this.getPreloadMainLinks()}
{this.getCssLinks()} {this.getCssLinks()}
{styles || null} {styles || null}
{this.props.children} {children}
</head> </head>
} }
} }
......
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