stitchesjs / stitches

[Not Actively Maintained] CSS-in-JS with near-zero runtime, SSR, multi-variant support, and a best-in-class developer experience.

Home Page:https://stitches.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

getCssText() is missing CSS on first SSR load

blechatellier opened this issue · comments

I've created a sample repo using vite, stitches and express for SSR. I'm running into an issue where the CSS from getCssText() is missing on first page load (after a server start) and then loads correctly on a subsequent page load.

First load
<style></style>

Second load
<style>--sxs{--sxs:2 c-dkEfkH}@media{.c-dkEfkH{background-color:red}}</style> 

Repo
https://github.com/blechatellier/stitches-vite-ssr

pnpm i
node .

Answering my own question here, after reading https://shud.in/posts/ssr-streaming-and-css-in-js I need to do a two-pass rendering to first generate the html with classes then render the styles. Will push an update to the repo with the solution if anyone stumbles on the same issue.

In server.jsx

export function render() {
  return ReactDOMServer.renderToString(<Button>Hello World</Button>);
}

export function renderStyle() {
  return ReactDOMServer.renderToString(
    <style id="stitches" dangerouslySetInnerHTML={{ __html: getCssText() }} />
  );
}

Then in server.js

  const appHtml = await server.render();
  const style = await server.renderStyle();

  const html = template
    .replace("<!--root-->", appHtml)
    .replace("<!--head-->", style);

Thanks @blechatellier. Your tip saved me a lot of time.