Skip to main content

Server-Side Rendering

Griffel provides first class support for Server-Side Rendering.

Next.jsโ€‹

Base setupโ€‹

For basic instructions to setup Next.js, see Getting Started. Please complete the following steps:

  1. Get a basic Next.js setup running, rendering a page from the pages folder, as guided by the tutorial.
  2. Add the Griffel to dependencies (@griffel/react package), check Install page.

A complete demo project is available on CodeSandbox.

Configuring a projectโ€‹

  1. Create a _document.js file under your pages folder with the following content:
import { createDOMRenderer, renderToStyleElements } from '@griffel/react';
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({
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;
  1. Create or modify an _app.js file under your pages folder with the following content:
import { createDOMRenderer, RendererProvider } from '@griffel/react';

function MyApp({ Component, pageProps, renderer }) {
return (
// ๐Ÿ‘‡ accepts a renderer passed from the <Document /> component or creates a default one
<RendererProvider renderer={renderer || createDOMRenderer()}>
<Component {...pageProps} />
</RendererProvider>
);
}

export default MyApp;
  1. You should now be able to server render components with Griffel styles on any of your pages:
import { makeStyles } from '@griffel/react';

const useClasses = makeStyles({
button: { fontWeight: 'bold' },
});

export default function Home() {
const classes = useClasses();

return <Button className={classes.button}>Hello world!</Button>;
}