import Layout from 'lib/components/layout'
import { Code, Link, Spacer, Note } from 'components'

export const meta = {
  title: 'Server Render',
  group: 'getting-started',
  index: 15,
}

## Server Render

### Geist UI on the Server

All Components of `@geist-ui/react` are compatible with **Server Render**. In fact, the document you see now is rendered by the server.

<Note label="readme">
  If you are looking to build a SPA{' '}
  <Link href="https://en.wikipedia.org/wiki/Single-page_application" rel="nofollow" underline>
    (single page application)
  </Link>
  , please feel free to skip this section.
</Note>

<Spacer y={0.5} />

If you are concerned about losing the advantages of a Single Page Application by implementing server-side rendering, you can use the `hybrid render` application.
Please read <Link color href="https://nextjs.org/blog/next-9-3#next-gen-static-site-generation-ssg-support" rel="nofollow">
the post from the Next.js team</Link> to learn more.

<Spacer y={2.5} />

### Next.js

In `next.js` framework, you need customization file `_document.js`,
please refer to <Link href="https://nextjs.org/docs/advanced-features/custom-document" rel="nofollow">Next.js document here</Link>
to create file `_document.js`.

Then we add the following code to the file:

```js
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { CssBaseline } from '@geist-ui/react'

class MyDocument extends Document {
  static async getInitialProps (ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    const styles = CssBaseline.flush()

    return {
      ...initialProps,
      styles: (
        <>
          {initialProps.styles}
          {styles}
        </>
      )
    }
  }

  render() { ... }
}
```

Here's an example of what your `_document.js` file should look like: <Link href="https://github.com/unix/unix.bio/blob/template/pages/_document.jsx" rel="nofollow">\_document.jsx</Link>.

<Spacer y={3} />

### Custom Server

In the custom server, also get the style set from function `CssBaseline.flush` as shown below.

```js
import React from 'react'
import ReactDOM from 'react-dom/server'
import { CssBaseline } from 'geist-ui/react'
import App from './app'

export default (req, res) => {
  const app = ReactDOM.renderToString(<App />)
  const styles = CssBaseline.flush()
  const html = ReactDOM.renderToStaticMarkup(
    <html>
      <head>{styles}</head>
      <body>
        <div id="root" dangerouslySetInnerHTML={{ __html: app }} />
      </body>
    </html>,
  )
  res.end('<!doctype html>' + html)
}
```

export default ({ children }) => <Layout meta={meta}>{children}</Layout>
