Server Side Rendering

Vanilla: Server-Side Rendering

1import { renderToString } from 'react-dom/server';
2import { createStylesheet } from '@filbert-js/server-stylesheet';
3import App from './App';
4
5const sheet = createStylesheet();
6const app = renderToString(sheet.collectStyles(<App />));
7const styleHTML = sheet.getStyles();
8// Or
9// const styleTags = sheet.getReactElements(); // give React elements
10
11const html = `
12<html>
13 <head>${styleHTML}</head>
14 <body>
15 <div id="app">${app}</div>
16 </body>
17</html>
18`;

Next.js: Server-Side Rendering

In Next.js world, create a file pages/_document.js

1// pages/_document.js
2
3import Document from 'next/document';
4import { createStylesheet } from '@filbert-js/server-stylesheet';
5
6class MyDocument extends Document {
7 static async getInitialProps(ctx) {
8 const sheet = createStylesheet();
9 const originalRenderPage = ctx.renderPage;
10 try {
11 ctx.renderPage = () =>
12 originalRenderPage({
13 enhanceApp: (App) => {
14 return (props) => {
15 return sheet.collectStyles(<App {...props} />);
16 };
17 },
18 });
19 const initialProps = await Document.getInitialProps(ctx);
20
21 const styleTags = sheet.getReactElements();
22 return {
23 ...initialProps,
24 styles: (
25 <>
26 {styleTags}
27 {initialProps.styles}
28 </>
29 ),
30 };
31 } finally {
32 }
33 }
34}
35
36export default MyDocument;

Check out official nextjs example

Gatsby.js: Server-Side Rendering

In Gatsby.js world, create a file gatsby-ssr.js

1// gatsby-ssr.js
2import { createStylesheet } from '@filbert-js/server-stylesheet';
3
4const sheetByPathname = new Map();
5
6export const wrapRootElement = ({ element, pathname }) => {
7 const sheet = createStylesheet();
8 sheetByPathname.set(pathname, sheet);
9 return sheet.collectStyles(element);
10};
11
12export const onRenderBody = ({ setHeadComponents, pathname }) => {
13 const sheet = sheetByPathname.get(pathname);
14 if (sheet) {
15 const styleTags = sheet.getReactElements();
16 setHeadComponents(styleTags);
17 sheetByPathname.delete(pathname);
18 }
19};

Or

Directly use gatsby-plugin-filbert