• Guides
  • Server-side rendering

Server-side rendering

The getSandpackCssText function, which is available in the main package, is responsible for getting the Sandpack CSS string and server-side render it. Furthermore, Sandpack uses stitches/core under the hood to generate and dedupe theme variation, ensuring a consistent and lightweight CSS output.

import { getSandpackCssText } from "@codesandbox/sandpack-react";
 
const cssTextOutput = getSandpackCssText();

How to use it

Here's some examples of how to use in some popular React frameworks.

💡

For a better hydration strategy, we highly recommend adding an id="sandpack" to your style tag.

Next.js (app dir)

See the example project


// components/sandpack-styles.tsx
"use client";
 
import { getSandpackCssText } from "@codesandbox/sandpack-react";
import { useServerInsertedHTML } from "next/navigation";
 
/**
 * Ensures CSSinJS styles are loaded server side.
 */
export const SandPackCSS = () => {
  useServerInsertedHTML(() => {
    return (
      <style
        dangerouslySetInnerHTML={{ __html: getSandpackCssText() }}
        id="sandpack"
      />
    );
  });
  return null;
};

// app/layout.tsx
 
import { SandPackCSS } from "@/components/sandpack-styles";
 
export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode,
}) {
  return (
    <html lang="en">
      <head>
        <SandPackCSS />
      </head>
      <body>{children}</body>
    </html>
  );
}

import { Sandpack } from "@codesandbox/sandpack-react";
 
export default function Home() {
  return (
    <div>
      <Sandpack theme="dark" />
    </div>
  );
}

Next.js

See the example project


// pages/_document.tsx
 
import { getSandpackCssText } from "@codesandbox/sandpack-react";
import { Html, Head, Main, NextScript } from "next/document";
 
export default function Document() {
  return (
    <Html>
      <Head>
        <style
          dangerouslySetInnerHTML={{ __html: getSandpackCssText() }}
          id="sandpack"
          key="sandpack-css"
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

Gatsby

See the example project

// gatsby-ssr.js
import * as React from "react";
import { getSandpackCssText } from "@codesandbox/sandpack-react";
 
export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <style
      id="sandpack"
      key="sandpack-css"
      dangerouslySetInnerHTML={{
        __html: getSandpackCssText(),
      }}
    />,
  ]);
};

Examples

Still not clear, take a look at these examples.