Skip to content

Commit

Permalink
Fix document head with react 18 (#37443)
Browse files Browse the repository at this point in the history
Fix custom head on getInitialProps works with React 18

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
  • Loading branch information
tbvjaos510 and huozhi committed Jun 4, 2022
1 parent 4cbc61c commit 3e5b025
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
1 change: 1 addition & 0 deletions packages/next/server/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1455,6 +1455,7 @@ export async function renderToHTML(
let styles
if (hasDocumentGetInitialProps) {
styles = docProps.styles
head = docProps.head
} else {
styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
Expand Down
14 changes: 13 additions & 1 deletion test/e2e/next-head/app/pages/_document.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Html, Head, Main, NextScript } from 'next/document'
import Document, { Html, Head, Main, NextScript } from 'next/document'

export default function MyDocument() {
return (
Expand All @@ -11,3 +11,15 @@ export default function MyDocument() {
</Html>
)
}

MyDocument.getInitialProps = async (context) => {
const initialProps = await Document.getInitialProps(context)

return {
...initialProps,
head: [
...(initialProps?.head ?? []),
<meta name="test-head-initial-props" content="hello" />,
],
}
}
13 changes: 9 additions & 4 deletions test/e2e/next-head/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@ describe('should set-up next', () => {
pages: new FileRef(join(__dirname, 'app/pages')),
components: new FileRef(join(__dirname, 'app/components')),
},
dependencies: {
react: '17',
'react-dom': '17',
},
})
})
afterAll(() => next.destroy())
Expand Down Expand Up @@ -62,4 +58,13 @@ describe('should set-up next', () => {
).toBe('hello')
}
})

it('should have current head tags from a _document getInitialProps', async () => {
const html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)

expect($(`meta[name="test-head-initial-props"]`).attr()['content']).toBe(
'hello'
)
})
})

0 comments on commit 3e5b025

Please sign in to comment.