Skip to Content
vitus·labs
Guides

SSR & Static Export

Run the UI system under the Next.js App Router, server rendering and `output: 'export'`. Covers where init() goes, how styles reach the HTML, and how to stay hydration-safe.

This guide sets up a Next.js App Router project (including a fully static output: 'export' build) with the styler engine. The approach also works for any React 19 server renderer.

This documentation site is built exactly this way. It is a static export, and its landing page is rendered with rocketstyle, elements and coolgrid. The snippets below are simplified from its source.

How the pieces fit

  • init() configures a module-level singleton. @vitus-labs/core exports one config object. init() stores the connector's css, styled, provider, keyframes, createGlobalStyle and useTheme on it, plus the platform defaults (component, textComponent). Every package reads the engine from that object. See Core.
  • Each module graph has its own singleton. Next.js bundles server components, the server render of client components, and the browser bundle as separate module graphs. UI-system code only runs in the client graph (used for both the server render and the browser), and that is where init() has to run.
  • init() is safe to call repeatedly. Calling it again with the same connector just stores the same references again. Calling it from several entry points costs nothing.
  • Order of imports does not matter at definition time. config.css and config.styled are lazy delegates: css and styled used at module level before init() return a thunk or a lazy component that resolves on first render. Only rendering before init() throws (CSS engine not configured).

1. A side-effect init module

src/ui/init.ts
import * as connector from '@vitus-labs/connector-styler'
import { init } from '@vitus-labs/core'

// Every module in src/ui imports this for its side effect, so whichever
// module graph renders a ui-system component has the engine configured.
init({ ...connector, component: 'div', textComponent: 'span' })

2. Keep it out of server components

Don't import the UI system from a server component

@vitus-labs/core creates its React context when the module loads. The React build used for server components (layouts, pages, route handlers, opengraph-image) has no createContext, so importing @/ui/init — or anything that pulls in core, such as @vitus-labs/hooks — from the root layout fails the build. Server components render your 'use client' UI components; they never import the engine themselves.

Need a ui-system fact at build time in a server module (a version, a count)? Read the package's package.json or type declarations from disk instead of importing its runtime.

3. Import it from every client boundary

UI-system components use React context and hooks, so they render as client components. The client graph is used both for the server render and in the browser. Import the init module from the providers file and from each component module:

src/ui/Providers.tsx
'use client'

import './init'
import { Provider } from '@vitus-labs/unistyle'
import type { ReactNode } from 'react'
import { theme } from './theme'

export function UIProvider({ children }: { children: ReactNode }) {
  // unistyle's Provider sorts breakpoints, builds the media helpers and
  // hands off to core's Provider → styler's ThemeProvider.
  return <Provider theme={theme}>{children}</Provider>
}
src/ui/Button.tsx
'use client'

import './init'
import { Element } from '@vitus-labs/elements'
import { rocketstyle } from '@vitus-labs/rocketstyle'

export const Button = rocketstyle()({ name: 'Button', component: Element })
  .attrs({ tag: 'button' })
  // .theme(…).states(…).sizes(…).styles(…)

Wrap the routes that use the UI system:

src/app/(home)/layout.tsx
import type { ReactNode } from 'react'
import { UIProvider } from '@/ui/Providers'

export default function Layout({ children }: { children: ReactNode }) {
  return <UIProvider>{children}</UIProvider>
}

Keep functions on the client side of the boundary

Server components can render your 'use client' components, but they can only pass serializable props. Function props such as css={(css) => css`…`} or a component type passed as beforeContent cannot cross from a server component. Define those inside client modules, for example as part of the component's .attrs() / .styles() chain.

Static export

next.config.mjs
/** @type {import('next').NextConfig} */
const config = {
  output: 'export',
}

export default config

Static export needs no extra setup. Every page is server-rendered at build time with the same pipeline described below, so the exported .html files already contain the CSS each page needs. No style registry and no _document collection step are needed.

How styles reach the HTML

Styler uses React 19's <style precedence> support (see Styler API: SSR):

  • On the server, each styled component renders a <style href={className} precedence="medium"> element next to its output. React hoists these into <head>, dedupes them by href and orders them by precedence. This works with streaming too.
  • createGlobalStyle components render <style precedence="low">, so global rules come before component rules.
  • keyframes rules are shipped inside the precedence tag of every component or global style whose CSS references them. An animation therefore works in the server HTML without extra wiring.
  • On hydration, the client sheet reads the data-href tokens React wrote and seeds its dedup cache, so rules already in the HTML are not injected a second time.

Render global styles inside the client provider tree, so they can read the theme:

src/ui/GlobalStyles.tsx
'use client'

import './init'
import { createGlobalStyle } from '@vitus-labs/styler'

export const GlobalStyles = createGlobalStyle`
  *, *::before, *::after { box-sizing: border-box; }
  body {
    margin: 0;
    font-family: ${({ theme }) => theme.fontFamily?.base ?? 'system-ui'};
  }
`
<Provider theme={theme}>
  <GlobalStyles />
  {children}
</Provider>

useCSS emits nothing on the server

useCSS() returns a deterministic class name during SSR, but it has no element to carry a <style precedence> tag, so its rules are only injected after hydration. Use styled() (or a rocketstyle/elements component) for anything that must be styled in the server HTML.

Do I need createSheet()?

Not with the default path. Component and global CSS travel inside React's <style precedence> tags, not through a shared buffer, so nothing leaks between requests. createSheet() and sheet.reset() are only needed for the manual SSR mode, for renderers that cannot process <style precedence>.

Hydration-safe hooks

The hooks that read browser-only state use useSyncExternalStore with a server snapshot. The server and the hydrating client render the same value, then React re-renders with the real one right after hydration:

HookServer and hydration valueAfter hydration
useMediaQuery(query)falseLive matchMedia result
useColorScheme()'light'OS preference
useReducedMotion()falseOS preference
useBreakpoint()Smallest breakpoint from the themeCurrent viewport's breakpoint
useLocalStorage(key, initial)initialStored value
useIsClient()falsetrue

Client-only renders (no SSR) get the real value on the first render.

Because the first paint uses the server value, a layout that branches in JavaScript (useBreakpoint() === 'xs' ? <Mobile /> : <Desktop />) shows the mobile layout until hydration. Prefer responsive props and theme values for layout. They compile to @media rules that are correct in the static HTML. See Responsive Layouts.

The same applies to dark mode: useColorScheme() renders 'light' in static HTML. See Theming & Dark Mode for ways to avoid a flash of the light theme.

Checklist

  • One init.ts side-effect module, imported from every 'use client' module that defines or provides UI-system components — never from a server component.
  • The theme provider (unistyle, coolgrid or rocketstyle Provider) lives in a 'use client' file.
  • Function props stay inside client modules.
  • Global styles are rendered inside the provider tree.
  • Layout uses responsive values instead of branching on useBreakpoint() / useMediaQuery().
Edit on GitHub

Last updated on

On this page