_document.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 = () => originalRenderPage({
  20. enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
  21. })
  22. const initialProps = await Document.getInitialProps(ctx)
  23. return {
  24. ...initialProps,
  25. styles: (
  26. <>
  27. {initialProps.styles}
  28. {sheet.getStyleElement()}
  29. </>
  30. )
  31. }
  32. } finally {
  33. sheet.seal()
  34. }
  35. }
  36. }
  37. export default MyDocument