_document.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * _document is only rendered on the server
  3. * https://github.com/zeit/next.js/#custom-document
  4. *
  5. * We're using styled-components, so here is the right place
  6. * to place the styles.
  7. * https://www.styled-components.com/docs/advanced#server-side-rendering
  8. *
  9. * Configure babel for server-side rendering with styled-components
  10. * https://dev.to/aprietof/nextjs--styled-components-the-really-simple-guide----101c
  11. */
  12. import Document from 'next/document'
  13. import { ServerStyleSheet } from 'styled-components'
  14. class MyDocument extends Document {
  15. static async getInitialProps (ctx) {
  16. const sheet = new ServerStyleSheet()
  17. const originalRenderPage = ctx.renderPage
  18. try {
  19. ctx.renderPage = () =>
  20. originalRenderPage({
  21. enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
  22. })
  23. const initialProps = await Document.getInitialProps(ctx)
  24. return {
  25. ...initialProps,
  26. styles: (
  27. <>
  28. {initialProps.styles}
  29. {sheet.getStyleElement()}
  30. </>
  31. )
  32. }
  33. } finally {
  34. sheet.seal()
  35. }
  36. }
  37. }
  38. export default MyDocument