Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

Rendering: server and client

What runs on the server, what runs in the browser, and how to set up the Provider so the two agree. The examples are for Next.js App Router, which is what this site runs.

Where code runs#

The whole @kvirn-ui/react entry is a client entry. The server entry is a separate import path.

EntryRuns whereFrom a Server Component
@kvirn-ui/reactClient (a 'use client' entry). Server-rendered to HTML, then hydrated.Render parts and components by their flat names (AlertTitle, TabsList). Do not call hooks.
@kvirn-ui/react/serverServer. No 'use client' and no client JavaScript.Yes: KvirnThemeScript, getLocaleProps, getMessages, createMessageFormat.
@kvirn-ui/coreAnywhere. No React, and no window or document when it is imported.Yes.
@kvirn-ui/i18n/<locale>Anywhere. A catalog is an object of functions.Import it, but do not pass it as a prop to a client component.
@kvirn-ui/themeCSS only.Yes: import theme.css in the layout.

Server Components#

Every export of @kvirn-ui/react is a client reference when a Server Component imports it. You can render it. It is server-rendered to HTML like any other component, and it hydrates in the browser. The pages of this site are Server Components that render Heading, Link and Table this way.

Use the flat exports

A Server Component can't read a property of a client reference, so Alert.Title fails there. Import the flat name instead: AlertTitle, TabsList, FieldRoot. It is the same component. Examples in these docs use the dotted form, which works in a client file.

// A Server Component: no 'use client', no hooks
import { AlertInfo, AlertTitle } from '@kvirn-ui/react'

export function Notice() {
  return (
    <AlertInfo>
      <AlertTitle as="h3">The service is slower than usual today</AlertTitle>
    </AlertInfo>
  )
}

What crosses the boundary

Props from a Server Component to a client component are serialised. Strings, numbers, plain objects and children cross. Functions do not, so an onClick belongs in a client file. A hook can only be called in a client file, so useButton(), useTheme() and the others are not available in a Server Component. Build that markup from the part components instead.

The as prop

There is no render prop. A part's element is the as prop. It takes a tag string, or a component that is a client reference. It never takes an element or an inline function: the types do not accept an element, and a server component or an inline function throws.

<AlertTitle as="p">Saved</AlertTitle>   // a tag string: fine
<LinkRoot as={MyClientLink} href="/a" />   // a client reference: fine
<LinkRoot as={MyServerComponent} />   // a server component or an inline function: throws
<LinkRoot as={<a />} />   // an element: not accepted

next/link is a plain server wrapper on the server, not a client reference. Import it in a 'use client' module, and use it as as or as the Provider's linkComponent from there.

Texts and formats in a Server Component

@kvirn-ui/react/server has the server versions of what the hooks give.getMessages is useMessages for one namespace. createMessageFormat is the formatter behind useFormat.

import { getMessages, createMessageFormat } from '@kvirn-ui/react/server'
import { sv } from '@kvirn-ui/i18n/sv'

const texts = getMessages('alert', { locale: 'sv-SE', messages: sv, timeZone: 'Europe/Stockholm' })
const format = createMessageFormat({ locale: 'sv-SE', timeZone: 'Europe/Stockholm' })

Client Components and hooks#

Hooks and anything with state or an event handler go in a file that starts with 'use client'. The Provider's hooks (useLocale, useDateSettings, useFormat, useTheme) read the nearest provider, so they work in that file.

'use client'
import { useLocale, useTheme } from '@kvirn-ui/react'

export function ThemeLabel() {
  const { locale } = useLocale()
  const { colorScheme } = useTheme()
  return <p lang={locale}>{colorScheme}</p>
}

Without a provider the hooks use English, left-to-right text and UTC, and useTheme still works. See the KvirnProvider page for what each hook returns.

The Provider in a Next.js app#

KvirnProvider is a client component and the layout is a Server Component. Props that are strings, numbers or plain objects pass from the layout. Catalogs, linkComponent, icons, a custom theme.storage and env do not, so put those in one small client wrapper. The KvirnProvider page has the full list and why.

app/kvirn-provider.tsx
'use client'
import { KvirnProvider } from '@kvirn-ui/react'
import type { KvirnProviderProps } from '@kvirn-ui/react'
import { sv } from '@kvirn-ui/i18n/sv'
import NextLink from 'next/link'
import { icons } from './icons' // a 'use client' module that calls defineIcons

export function AppKvirnProvider(
  props: Omit<KvirnProviderProps, 'messages' | 'linkComponent' | 'icons' | 'env'>,
) {
  return <KvirnProvider {...props} messages={sv} linkComponent={NextLink} icons={icons} />
}
app/theme.tsone object for the script and the provider
export const theme = {
  defaultColorScheme: 'system',
  defaultContrast: 'system',
  defaultMotion: 'system',
} as const
app/layout.tsxa Server Component
import { KvirnThemeScript, getLocaleProps } from '@kvirn-ui/react/server'
import { headers } from 'next/headers'
import type { ReactNode } from 'react'
import { AppKvirnProvider } from './kvirn-provider'
import { theme } from './theme'

const locale = 'sv-SE'

export default async function RootLayout({ children }: { children: ReactNode }) {
  const nonce = (await headers()).get('x-nonce') ?? undefined
  const { lang, dir } = getLocaleProps(locale)

  return (
    <html lang={lang} dir={dir} suppressHydrationWarning>
      <head>
        <KvirnThemeScript nonce={nonce} theme={theme} />
      </head>
      <body>
        <AppKvirnProvider locale={locale} timeZone="Europe/Stockholm" weekStart={1} theme={theme}>
          {children}
        </AppKvirnProvider>
      </body>
    </html>
  )
}

getLocaleProps sets lang and dir on <html>, because the provider renders no element of its own and can't set the page language (WCAG 3.1.1). suppressHydrationWarning on <html> is on purpose, see the next section.

No flash of the wrong theme#

The theme preference lives in localStorage (or in memory with storage: 'none'). The server can't read it. Two things cover the first paint.

  • The theme's CSS follows prefers-reduced-motion until an attribute says otherwise. Colour scheme and contrast come from the attributes alone, so without JavaScript the page is the light, standard theme.
  • KvirnThemeScript is a small blocking inline script in <head>. It reads the stored choice and sets data-kv-color-scheme, data-kv-contrast and data-kv-motion on <html> before the first paint.

That is why the server markup and the page differ on purpose, and why the layout has suppressHydrationWarning. It only affects the attributes of <html> itself. Pass the script the same theme object as the provider. It reads localStorage only, so don't render it with a custom storage adapter.

Render the script only in the server-rendered document: React never runs a script it creates in the browser, and warns in development if it does. In an app that renders only in the browser, the provider applies the theme when it mounts, so the default theme can show for a moment.

If you keep the choice in your own cookie, the server can write the attribute itself, with no script. Write one only for an explicit choice, and leave it out for system. The recipe is in the repo's KvirnProvider guide (kvirn-provider.md, Cookie storage adapter recipe).

<html lang={lang} dir={dir} data-kv-color-scheme="dark">

Time zones and dates#

The server and the browser can be in different time zones. Set timeZone on the provider, the same on both, and an instant reads the same in the server HTML and after hydration. Without one, instants are shown in UTC, never the runtime's zone, so the two renders still agree. The first instant shown without a zone logs a warning in development. A date-only instant then carries no zone label and can show the neighbouring day: for a calendar date use the YYYY-MM-DD string. A Calendar's “today” is the UTC date on first paint and the browser's date after mount.

Set weekStart explicitly for the same reason: a runtime without Intl week data can answer Monday where another answers Sunday. A date written YYYY-MM-DD is a calendar date and is shown on that day in every zone. See Locales and strings for formatting.

Strict CSP#

A strict script-src without 'unsafe-inline' needs a nonce on the inline theme script. Make the nonce in proxy.ts, send it on as x-nonce, and read it in the layout as above.

proxy.tsmiddleware.ts before Next 16
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function proxy(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
  const policy = [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,
    "style-src 'self' 'unsafe-inline'",
    "object-src 'none'",
    "base-uri 'self'",
  ].join('; ')

  const requestHeaders = new Headers(request.headers)
  requestHeaders.set('x-nonce', nonce)
  requestHeaders.set('Content-Security-Policy', policy)

  const response = NextResponse.next({ request: { headers: requestHeaders } })
  response.headers.set('Content-Security-Policy', policy)
  return response
}

// Skip static assets and prefetches: they need no nonce
export const config = {
  matcher: [
    {
      source: '/((?!_next/static|_next/image|favicon.ico).*)',
      missing: [{ type: 'header', key: 'next-router-prefetch' }],
    },
  ],
}

Warning: Don't forget

Reading headers() makes every page dynamic, because a nonce is made per request and a static page can't carry one. This site turns the nonce on only when it is built with DOCS_CSP_NONCE=1, so its default build stays static. With it on, the script runs and hydration reports no mismatch.

Other frameworks and plain SSR#

The repo checks Next.js App Router in this site, and checks server rendering with renderToString and then hydrateRoot in its tests. That covers the provider, a time zone, a nested section in another language, the theme script under a nonce-only CSP and useTheme without a provider. The tests report no hydration error. Other frameworks are not tested here.

import { renderToString } from 'react-dom/server'
import { hydrateRoot } from 'react-dom/client'
import { KvirnProvider } from '@kvirn-ui/react'

const app = (
  <KvirnProvider locale="sv-SE" timeZone="Europe/Stockholm">
    <App />
  </KvirnProvider>
)

// on the server
const html = renderToString(app)

// in the browser, on the markup the server sent
hydrateRoot(document.getElementById('root'), app)
  • During server rendering there is no window or document, so env is undefined and the provider gives its defaults. It uses the page's own window and document after hydration. Set env only for an iframe or a test.
  • Render KvirnThemeScript in the document's head if you render on the server, with the response's nonce.
  • Set lang and dir on <html> yourself with getLocaleProps.