Skip to content

Instantly share code, notes, and snippets.

@nitin42
Created July 11, 2017 15:25
Show Gist options
  • Save nitin42/559fe988c59194357ce868416c390273 to your computer and use it in GitHub Desktop.
Save nitin42/559fe988c59194357ce868416c390273 to your computer and use it in GitHub Desktop.
server side rendering with glamorous

server side rendering

To perform server-side rendering, use renderStatic from glamor, which takes a callback. Render your component inside the callback and all of the calls to css() will be collected and generated html and css will be returned. This will also return an array of ids to rehydrate the styles for fast startup.

To perform rehydration, call rehydrate with the array of ids returned by renderStatic.

Example -

import { renderStatic } from 'glamor/server';
import { rehydrate } from 'glamor';
import { render } from 'react-dom';
import ReactDOMServer from 'react-dom/server';

let { html, css, ids } = renderStatic(() => ReactDOMServer.renderToString(<App />))

return `
  <html>
    <head>
      <style>${css}</style>
    </head>
    <body>
      <div id="app">${html}</div>
      <script src="./bundle.js"></script>
      <script>
        rehydrate(${JSON.stringify(ids)});
        render(<App />, document.getElementById('app'));
      </script>
    </body>
  </html>
`

Usage with Next.js

Check out this example on how to use glamorous with Next.js

Using rehydrate

Glamorous might add duplicate styles to the page due to the intricate nature of es6 imports.

For example -

import App from './App';

rehydrate(${JSON.stringify(ids)}); // ids returned by renderStatic

As import statements get transpiled before other statements, so rehydrate will be called after regardless of what order you list the statements. This will result in duplicate styles because App is imported first, so all the styles are added before rehydrate runs.

To tackle this problem, use a require() call to order the statements.

rehydrate(${JSON.stringify(ids)});

const App = require('./App');

Or rehydrate must be run before any other style code if you use any other solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment