SSR / foldkit-ssr

Serving pages

Through Foldkit's fetch handler

SSR.entry produces Foldkit's renderPage(request) handler for handleRequest on Node and Cloudflare Workers:

ts
import { handleRequest } from 'foldkit/experimental/server'

export const { renderPage } = SSR.entry(config, Post, { buildId })

export default {
  fetch: (request: Request) => handleRequest(request, { renderPage, template }),
}
ts
// vite.config.ts
import { foldkit } from '@foldkit/vite-plugin'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [foldkit({ ssr: { serverEntry: '/src/entry.server.ts' } })],
})

Pass the same deployment id to both entry.server.ts and your client entry (buildId: import.meta.env.FOLDKIT_BUILD_ID in Vite, or process.env.FOLDKIT_BUILD_ID in build scripts). When no environment variable is set during a single vite build, assign one in vite.config.ts before calling foldkit():

ts
import { randomUUID } from 'node:crypto'

process.env.FOLDKIT_BUILD_ID ??= randomUUID()

Without a matching buildId on both sides, SSR.hydrate contains the page and reports NoBuildId or OtherBuild (PageContained under Diagnostics) instead of decoding an envelope from another build.

Request handling in SSR.entry:

  • GET and HEAD: Runs flags(request) (when configured), init, prepare(model, request) (for Data.satisfy or reading request cookies), and redirect before rendering.
  • POST: Handled when the plan sets fallback: 'server' (Forms that work without scripts).
  • OPTIONS and other methods: Answers OPTIONS with 204 and other methods with 405 and an Allow header.
  • Errors: Failed renders, flags, prepare, or status callbacks answer 500 and report PageFailed (Diagnostics).

Use headers(request, model) to attach response headers (model is Option.some(reachedModel) on rendered pages and Option.none() on OPTIONS, 405, refused posts, or 500s):

ts
SSR.entry(config, Post, {
  buildId,
  headers: (_request, model) => ({
    'cache-control': 'private, no-store',
    vary: 'cookie',
    ...Option.match(model, {
      onNone: () => ({}),
      onSome: ({ post }) => ({
        'set-cookie': `last-read=${encodeURIComponent(post.id)}; Path=/; SameSite=Lax`,
      }),
    }),
  }),
})

Throwing inside headers, returning invalid header values, or setting response-framing headers (content-length, transfer-encoding, connection, location) returns 500. Always URL-encode Model values placed in cookies.

Use status(model, request) to return custom HTTP status codes (such as 404 for NotFound routes):

ts
SSR.entry(config, Post, {
  buildId,
  status: model =>
    AppRoute.match(model.route, { Home: () => 200, Post: () => 200, NotFound: () => 404 }),
})

Status codes outside 200–599, bodyless statuses (204, 205, 304), or thrown errors answer 500.

To move a plan's meta tags into <head> during dynamic serving, wrap the host's document renderer with SSR.headed:

ts
import { injectIntoTemplate, renderDocument as renderShell } from 'foldkit/experimental/server'

// Export as `renderDocument` from your Vite server entry:
const headedShell = SSR.headed(renderShell)

// Or wrap template injection:
const headedTemplate = SSR.headed((application: Parameters<typeof injectIntoTemplate>[1]) =>
  injectIntoTemplate(template, application),
)

SSR.headed moves the marked meta block at the end of the root into <head> per request (use SSR.keptDocuments(SSR.headed(render)) when caching rendered documents). Root tags that forbid <meta> (void tags, tables, <svg>, raw text) fail with RootRefusesHead; omitting SSR.headed triggers HeadNotMoved on hydration.

What the host hands the page: SSR.requestContext

Because handleRequest invokes renderPage(request) with no env parameter, use SSR.requestContext to attach per-request dependencies (such as pageReader) in your Worker or Node host and read them inside prepare:

ts
import { Effect, Option, type Layer } from 'effect'
import type { RemoteClient, RemoteUnauthenticated } from 'foldkit-remote'
import { SSR } from 'foldkit-ssr'

// Shared module imported by both the host and server entry.
export const PageContext = SSR.requestContext<{
  readonly reader: Layer.Layer<RemoteClient, RemoteUnauthenticated>
}>('app/page')

// Host attaches per request:
//   pages.fetch(PageContext.attach(request, { reader: pageReader(page)(request, env) }))

export const { renderPage } = SSR.entry(config, Post, {
  buildId,
  prepare: (model, request) =>
    Option.match(PageContext.of(request), {
      onNone: () => Effect.fail(new Error('No reader for this page.')),
      onSome: ({ reader }) => Data.satisfy(model, actives).pipe(Effect.provide(reader)),
    }),
})

PageContext stores values in a globalThis WeakMap keyed by registered symbol so separately bundled Worker and Vite page entries share values by context name without leaking across requests. Calling PageContext.attach twice with the same name on one Request throws, and copying a Request via new Request(request) drops attached context (PageContext.of returns Option.none()). See examples/auth (src/host.ts) for the full setup.

Sending a page elsewhere: redirect

For protected pages, redirect(model, request) inspects the prepared Model on GET and HEAD requests and returns Option.some(path) to answer with 303 before rendering the view (use answerPost for POST forms):

ts
export const guarded = SSR.entry(config, Post, {
  buildId,
  prepare: (model, request) =>
    Option.match(PageContext.of(request), {
      onNone: () => Effect.fail(new Error('No reader for this page.')),
      onSome: ({ reader }) => Data.satisfy(model, actives).pipe(Effect.provide(reader)),
    }),
  redirect: model =>
    Access.match(accessOf(model), {
      Denied: ({ url }) => Option.some(url),
      Allowed: () => Option.none(),
      Pending: () => Option.none(),
    }),
})

Redirects always set cache-control: private, no-store (bypassing cache while keeping any set-cookie or vary headers from headers). Return a same-origin path starting with a single / (never an absolute URL, //host, or /\host, which fail with 500).

Keeping pages: cache

Pages rendered solely from their URL are identical for every visitor. Pass cache to store and reuse public responses:

ts
import { CacheStore } from 'foldkit-surface'

export const cached = SSR.entry(config, Post, {
  buildId,
  cache: { store: CacheStore.memory(), maxAge: '60 seconds' },
})

For each GET request, SSR.entry tracks every header read by flags, prepare, redirect, headers, or status, as well as every pageReader read (PageReads):

  • Cached: When every read header was absent from the request, every pageReader read was public, status is 200, and headers set no cookie or custom cache-control, the page is stored under (buildId, url) with cache-control: public, max-age=… and vary listing the watched headers. Mutations answered by serveFetch sharing the store purge affected pages automatically.
  • Not cached: Requests carrying a watched header (such as a session or cart cookie), calling request.clone(), reading SSR.requestContext, or returning cookies or non-200 statuses receive cache-control: private, no-store.

On Cloudflare Workers, use CacheStore.workers(caches.default) or CacheStore.kv(env.CACHE, { keep: '6 hours' }) (which serves stale HTML for keep while clients refresh past maxAge via Remote). Wrap renderDocument with SSR.keptDocuments(SSR.headed(renderShell)) to cache the last 32 template injections per asset set.

Verify cache safety in development with cache.check (re-renders and reports CachedPageDiffers on mismatch, ignoring 13-digit timestamps) or in tests with SSR.checkCache:

ts
export const checked = SSR.checkCache(
  options => SSR.entry(config, Post, { buildId, ...options }),
  [
    () => new Request('https://example.com/posts/1'),
    () => new Request('https://example.com/posts/1', { headers: { cookie: 'session=abc' } }),
  ],
)

At build time

Generate static HTML files, a sitemap, and robots.txt for fixed routes:

ts
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'

const pages = await Effect.runPromise(
  SSR.generate(config, Post, {
    buildId,
    template,
    origin: 'https://example.com',
    paths: ['/', '/about', '/docs/intro'],
  }),
)
for (const page of pages) {
  await mkdir(dirname(join('dist', page.file)), { recursive: true })
  await writeFile(join('dist', page.file), page.html)
}

Paths map to <path>/index.html (or keep .html filenames). Generated pages record their path without query parameters, so /about?ref=mail still resumes and applies routing.onUrlChange immediately at boot before URL mirrors run.

ts
await writeFile(
  'dist/sitemap.xml',
  SSR.sitemap(
    pages.map(page => ({ path: page.path, modified: '2026-09-27' })),
    { origin: 'https://example.com' },
  ),
)
await writeFile('dist/robots.txt', SSR.robots({ origin: 'https://example.com' }))

SSR.sitemap rejects duplicate paths, paths missing a leading /, or invalid dates. SSR.robots supports disallow and custom sitemap paths.

As a Vite plugin: foldkit-ssr/vite

staticSite runs the static build during Vite's closeBundle step by loading a SiteModule (src/site.ts):

ts
// vite.config.ts
import { foldkit } from '@foldkit/vite-plugin'
import { staticSite } from 'foldkit-ssr/vite'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [foldkit(), staticSite({ site: { module: '/src/site.ts' } })],
})
ts
// src/site.ts
import { Style } from 'foldkit-mixins'
import type { SiteModule } from 'foldkit-ssr/vite'
export const site = {
  origin: 'https://example.com',
  paths: ['/', '/about'],
  config,
  plan: Post,
  head: (_rendered, drawn) => `<style>${Style.usedDrawn(drawn)}</style>`,
  files: 'directory',
  sitemap: true,
  robots: true,
} satisfies SiteModule

config and plan can also be functions of path when pages belong to different apps. Pass plugins to staticSite({ site, plugins }) if your app relies on build plugins (such as Foldkit's view-identity branding) so generated HTML matches client hydration. Use emit to write extra assets like responsive image variants (foldkit-media's materialize) without colliding with pages or public/ files. Outside Vite, call generateStaticSite(site), writeEmitted(outDir, emitted), and fileFor(path, layout).

Pages rendered once, at build: prerendered

Routes that are identical for every visitor can be pre-rendered during vite build (ssr.build.prerender: true) so the host serves static HTML with zero server CPU. Export prerenderPaths and pass it to SSR.entry:

ts
export const prerenderPaths = ['/']

export const { renderPage } = SSR.entry(config, Post, { buildId, prerendered: prerenderPaths })
ts
// vite.config.ts
import { foldkit } from '@foldkit/vite-plugin'

foldkit({
  ssr: {
    serverEntry: '/src/entry.server.ts',
    clientEntry: '/src/entry.ts',
    build: { prerender: true },
  },
})

SSR.entry checks prerendered routes on every render (including dev): every pageReader read must be public, zero request headers may be inspected (even absent ones), status must be 200, and headers must emit nothing — otherwise renderPage fails and names the header or private read. Prerendered files record their path without query strings so /?q=… resumes in the browser, while dynamically rendered pages (such as search results in examples/foldkit/domains-plus that read cookies or ?q=) stay per-request.