import { Meta } from '@storybook/addon-docs/blocks';

<Meta title="Concepts/Developer/Server-Side Rendering" />

## Server-Side Rendering

Fluent UI fully supports Server-Side Rendering.

### Next.js

For basic instructions on getting Next.js set up, see [Getting Started](https://nextjs.org/docs/getting-started).

1. Get a basic next.js setup running, rendering a page from the `pages` folder, as guided by the tutorial.
2. Add the Fluent UI dependencies: `@fluentui/react-components`.

```sh
yarn add @fluentui/react-components@alpha
```

1. Create a `_document.js` file under your `pages` folder with the following content:

```tsx
import { createDOMRenderer, renderToStyleElements } from '@fluentui/react-components';
import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    // 👇 creates a renderer
    const renderer = createDOMRenderer();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
      originalRenderPage({
        // 👇 this is required by pass the same instance to <App />
        enhanceApp: App => props => <App {...props} renderer={renderer} />,
      });

    const initialProps = await Document.getInitialProps(ctx);
    const styles = renderToStyleElements(renderer);

    return {
      ...initialProps,
      // 👇 adding our styles elements to output
      styles: [...initialProps.styles, ...styles],
    };
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
```

2. Create or modify a `_app.js` file under your `pages` folder with the following content:

```js
import { createDOMRenderer, RendererProvider, SSRProvider } from '@fluentui/react-components';

function MyApp({ Component, pageProps, renderer }) {
  return (
    // 👇 accepts a renderer from <Document /> or creates a default one
    <RendererProvider renderer={renderer || createDOMRenderer()}>
      <SSRProvider>
        <Component {...pageProps} />
      </SSRProvider>
    </RendererProvider>
  );
}

export default MyApp;
```

3. You should now be able to server render Fluent UI React components in any of your pages:

```js
import { Button, FluentProvider, webLightTheme } from '@fluentui/react-components';

export default function Home() {
  return (
    <FluentProvider theme={webLightTheme}>
      <Button>Hello world!</Button>
    </FluentProvider>
  );
}
```
