Skip to content

Deploying

Build for production, host as a static site or under a subpath, and prerender pages to HTML.

docs/guides/deploying.md
Raw Markdown

This guide takes a Xote app from your machine to a host. It covers a plain client-side build, hosting under a subpath, and prerendering pages to static HTML so they load fast and can be indexed.

Build for production

Xote apps build with Vite. ReScript compiles each .res file to a .res.mjs file next to it, and Vite bundles those like any JavaScript.

Your index.html loads the compiled entry file:

1<body>
2 <div id="app"></div>
3 <script type="module" src="/src/Main.res.mjs"></script>
4</body>

The entry starts the router and mounts the app:

1// src/Main.res
2Router.init()
3View.mountById(<App />, "app")

Compile, then build:

1npx rescript && npx vite build

Vite writes the site to dist/. Everything in it is static, so any static host can serve it.

Host a client-only app

A client-only app has one HTML file, and the router picks the page in the browser. That works when a visitor starts at /. When they open /about directly or reload it, the host looks for an /about file, finds none, and returns a 404.

Tell the host to answer unknown paths with index.html. The setting depends on the host:

  • Netlify: add a public/_redirects file containing /* /index.html 200.
  • Vercel: add a rewrite from /(.*) to /index.html in vercel.json.
  • GitHub Pages: there is no rewrite setting. Copy dist/index.html to dist/404.html after the build, so unknown paths load the app (with a 404 status), or prerender every page as shown below.

Serve from a subpath

When the app lives under a path, such as https://example.com/my-app/, tell both Vite and the router.

In vite.config.mjs, set base so asset URLs include the path:

1import { defineConfig } from 'vite'
2
3export default defineConfig({
4 base: '/my-app/',
5})

In your entry, pass the same path to the router:

1Router.init(~basePath="/my-app", ())
2View.mountById(<App />, "app")

Your route patterns stay root-relative: /about still matches /my-app/about. Router.link and Router.push add the base path for you, so don't write it into your links.

Prerender pages to static HTML

Prerendering runs your app once per route at build time and saves the HTML. Visitors get a full page immediately, the browser then hydrates it to make it interactive, and every route exists as a real file, so no rewrite rules are needed. This docs site is deployed this way.

You need two entries. The server entry renders one URL to a string:

1// src/EntryServer.res
2let render = (url: string) => {
3 Router.initSSR(~pathname=url, ())
4 SSR.renderToString(() => <App />)
5}

The client entry hydrates the HTML that is already on the page instead of mounting from scratch:

1// src/EntryClient.res
2Router.init()
3Hydration.hydrateById(() => <App />, "app")

Point index.html at the client entry and leave a marker where the HTML goes:

1<div id="app"><!--ssr-outlet--></div>
2<script type="module" src="/src/EntryClient.res.mjs"></script>

Build the client, build the server entry, then run a short script that renders each route into the template:

1{
2 "scripts": {
3 "build": "rescript && vite build && vite build --ssr src/EntryServer.res.mjs --outDir dist-server && node scripts/prerender.mjs"
4 }
5}
1// scripts/prerender.mjs
2import fs from 'node:fs'
3import path from 'node:path'
4
5const routes = ['/', '/about']
6const template = fs.readFileSync('dist/index.html', 'utf-8')
7const { render } = await import(path.resolve('dist-server/EntryServer.res.js'))
8
9for (const route of routes) {
10 const html = template.replace('<!--ssr-outlet-->', render(route))
11 const file = route === '/' ? 'dist/index.html' : path.join('dist', route, 'index.html')
12 fs.mkdirSync(path.dirname(file), { recursive: true })
13 fs.writeFileSync(file, html)
14}

Upload dist/ as before. This site's own script builds on the same idea and also writes page titles, a sitemap and Markdown copies.

With a subpath, pass it to the server router too: Router.initSSR(~basePath="/my-app", ~pathname=url, ()), where url is the app-relative path such as /about.

Render on a server instead

If pages depend on the request, such as the signed-in user, render them on each request instead of at build time. The pieces are the same: Router.initSSR with the request's path, then SSR.renderToString or SSR.renderDocument. Server rendering walks through a full server, including how to send signal values to the client with SSRState.

Keep browser-only code out of the server

Prerendering and server rendering run your components in Node, where there is no window or document. Two tools keep shared code safe:

  • View.onMount New in 7.2 runs after the component is in the page, and never on the server. Put DOM work there, like focusing an input or measuring an element.
  • SSRContext tells you where code runs. SSRContext.isClient and SSRContext.isServer are constants you can branch on, and SSRContext.onClient(() => ...) runs a function only in the browser, returning Some of its result there and None on the server.
1let savedTheme = SSRContext.onClient(() => readThemeFromLocalStorage())

Common mistakes

  • No fallback on a client-only host. Links work, but reloading any page except / shows a 404. Add the rewrite, or prerender.
  • A base path in only one place. Set it in Vite's base and in Router.init, and leave it out of your links.
  • Mounting instead of hydrating prerendered pages. View.mountById renders from scratch. Use Hydration.hydrateById, which adopts the HTML that is already there.
  • Touching window at the top of a module. It runs during prerendering and crashes the build. Move it into View.onMount or SSRContext.onClient.

Summary

A Xote app deploys as Vite output. Three shapes exist: a client-only SPA (one index.html, needs a host rewrite to index.html for deep links), a prerendered site (each route rendered to static HTML at build time with SSR.renderToString, then hydrated in the browser with Hydration.hydrateById), and request-time server rendering (render per request with SSR.renderDocument). Subpath hosting requires the same base path in Vite's base and in Router.init/Router.initSSR. The one rule that matters most: anything that runs during prerendering or server rendering (every module the server entry imports) MUST NOT touch window/document outside View.onMount, SSRContext.onClient or an SSRContext.isClient guard.

Availability

ItemImport / entryFirst stableChanged in 7.2.0Needs the PPX
Router.init, Router.initSSR (with ~basePath)xote, xote/routerstable (all 7.x)—No
SSR.renderToString, SSR.renderDocumentxote, xote/ssrstable (all 7.x)—No
Hydration.hydrate, Hydration.hydrateByIdxote, xote/hydrationstable (all 7.x)—No
SSRStatexote, xote/ssr-state7.0.0—No
SSRContext (isServer, isClient, onClient, onServer, match)xote, xote/ssr-contextstable (all 7.x)—No
View.onMountxote7.2.0 (new)—No

Rules

  1. Build order: compile ReScript (rescript), then Vite (vite build). Vite bundles the compiled .res.mjs files; it does not compile .res.
  2. A client-only SPA MUST be served with a fallback that answers unknown paths with index.html; otherwise a reload or deep link to any route other than / returns 404.
  3. Base path: Vite base (for asset URLs) and Router.init(~basePath) (for routing) MUST name the same path. ~basePath is normalised (leading slash added, trailing slash removed); Vite's base should end with /.
  4. With a base path, route patterns and Router.push/Router.replace/Router.link targets stay app-relative (/about). Router.link and Router.Link render href with the base path prefixed; Router.location() returns the pathname with the base stripped. A plain <a href="/about"> is not prefixed and triggers a full page load.
  5. Server/prerender entry: call Router.initSSR(~pathname, ()) (plus ~basePath when used; ~pathname is app-relative) before SSR.renderToString, for every route rendered. initSSR sets the shared router state, including resetting basePath to "/" when omitted.
  6. Client entry for prerendered or server-rendered HTML MUST hydrate (Hydration.hydrateById(app, id)), not mount: View.mountById renders a second copy instead of adopting the markup. The component tree MUST be identical to the one rendered on the server; mismatches leave stale markup in place.
  7. SSR.renderToString returns the app's HTML without a container; the HTML template supplies the container (e.g. <div id="app"><!--ssr-outlet--></div>) and the client hydrates that id. SSR.renderDocument returns a full document and places the app inside <div id="root">; the client then hydrates "root".
  8. One prerender process renders many routes: module-level state (signals, resources, SSRState registry) persists between routes. Call SSRState.clear() per route/request and do not keep request data in module-level signals.
  9. Resources created during a server render do not fetch (they render Pending); data needed in the HTML must be loaded before rendering and transferred with SSRState (see the Fetching data guide).
  10. SSRContext.isServer is typeof document === 'undefined' evaluated when Xote loads. In Vite's SSR build run by Node it is true; in the browser false.
  11. View.onMount never runs on the server; in the browser it runs after hydration. Put DOM work (focus, measurement, localStorage) there or in SSRContext.onClient.
  12. Asset URLs written as string literals in code ("/logo.svg") are not rewritten by Vite's base; import the asset or prefix with Vite's import.meta.env.BASE_URL.

API

NameSignatureBehaviour
Router.init(~basePath: string=?, unit) => unitBrowser: reads the URL, listens to history. Call once in the entry.
Router.initSSR(~basePath: string=?, ~pathname: string=?, ~search: string=?, ~hash: string=?, unit) => unitServer: sets the location without browser APIs.
SSR.renderToString(unit => View.node, ~options: renderOptions=?) => stringApp HTML with hydration markers.
SSR.renderDocument(~head: string=?, ~bodyAttrs: string=?, ~scripts: array<string>=?, ~styles: array<string>=?, ~stateScript: string=?, ~nonce: string=?, unit => View.node) => stringFull HTML document; app inside <div id="root">.
Hydration.hydrateById(unit => View.node, string, ~options: hydrateOptions=?) => unitAdopts server markup in that element; no-op if the id is missing.
SSRState.clearunit => unitResets transferred state between renders.
SSRState.generateScript(~nonce: string=?) => string<script> with transferred state.
SSRContext.onClient(unit => 'a) => option<'a>Some result in the browser, None on the server.
SSRContext.match(~server: unit => 'a, ~client: unit => 'a) => 'aEnvironment-specific value.

Patterns

Client-only SPA — Use when: no SEO/first-paint requirement.

1<body>
2 <div id="app"></div>
3 <script type="module" src="/src/Main.res.mjs"></script>
4</body>
1// src/Main.res
2Router.init()
3View.mountById(<App />, "app")
1npx rescript && npx vite build # output: dist/

Host fallback (pick the host's mechanism):

  • Netlify: public/_redirects containing /* /index.html 200.
  • Vercel: vercel.json with {"rewrites": [{"source": "/(.*)", "destination": "/index.html"}]}.
  • GitHub Pages (no rewrites): copy dist/index.html to dist/404.html after the build (deep links load the app with HTTP 404), or prerender every route.

Subpath hosting — Use when: served at https://example.com/my-app/.

1// vite.config.mjs
2import { defineConfig } from 'vite'
3export default defineConfig({ base: '/my-app/' })
1// src/Main.res
2Router.init(~basePath="/my-app", ())
3View.mountById(<App />, "app")

Prerendered static site — Use when: routes are known at build time and pages should be indexable.

1// src/EntryServer.res
2let render = (url: string) => {
3 Router.initSSR(~pathname=url, ())
4 SSR.renderToString(() => <App />)
5}
1// src/EntryClient.res
2Router.init()
3Hydration.hydrateById(() => <App />, "app")
1<!-- index.html -->
2<div id="app"><!--ssr-outlet--></div>
3<script type="module" src="/src/EntryClient.res.mjs"></script>
1{
2 "scripts": {
3 "build": "rescript && vite build && vite build --ssr src/EntryServer.res.mjs --outDir dist-server && node scripts/prerender.mjs"
4 }
5}
1// scripts/prerender.mjs
2import fs from 'node:fs'
3import path from 'node:path'
4
5const routes = ['/', '/about']
6const template = fs.readFileSync('dist/index.html', 'utf-8')
7const { render } = await import(path.resolve('dist-server/EntryServer.res.js'))
8
9for (const route of routes) {
10 const html = template.replace('<!--ssr-outlet-->', render(route))
11 const file = route === '/' ? 'dist/index.html' : path.join('dist', route, 'index.html')
12 fs.mkdirSync(path.dirname(file), { recursive: true })
13 fs.writeFileSync(file, html)
14}

Vite names the SSR bundle after the entry with a .js extension (EntryServer.res.js). With a base path, pass it to both routers: Router.initSSR(~basePath="/my-app", ~pathname=url, ()) and Router.init(~basePath="/my-app", ()); url stays app-relative. The Xote docs site's own docs-website/scripts/prerender.mjs follows this procedure and adds per-route titles, a sitemap, redirect pages and Markdown copies.

Request-time rendering — Use when: HTML depends on the request (user, query).

1let renderRequest = (~pathname: string) => {
2 SSRState.clear()
3 Router.initSSR(~pathname, ())
4 SSR.renderDocument(
5 ~head="<title>My app</title>",
6 ~scripts=["/assets/client.js"],
7 ~stateScript=SSRState.generateScript(),
8 () => <App />,
9 )
10}
11// client: Router.init(); Hydration.hydrateById(() => <App />, "root")

Environment guards — Use when: shared code needs browser APIs.

1let savedTheme = SSRContext.onClient(() => readThemeFromLocalStorage()) // option<string>
2let label = SSRContext.match(~server=() => "server", ~client=() => "browser")

Anti-patterns

  1. No SPA fallback. Symptom: navigating inside the app works; reloading /about returns the host's 404. Right: configure the host rewrite, or prerender.

  2. Base path in one place only. Wrong: Vite base: '/my-app/' but Router.init(). Symptom: assets load, but no route matches (the router sees /my-app/about), or links point outside the app. Right: same path in both; links stay app-relative.

  3. Writing the base path into links. Wrong: Router.link(~to="/my-app/about", …). Symptom: href="/my-app/my-app/about". Right: ~to="/about".

  4. Mounting over prerendered HTML. Wrong: View.mountById(<App />, "app") in the client entry of a prerendered site. Symptom: the content appears twice, or flashes as it is rebuilt; server markup is not reused. Right: Hydration.hydrateById(() => <App />, "app").

  5. Browser API at module top level. Wrong: let width = window["innerWidth"] in a component module. Symptom: vite build --ssr succeeds but prerendering throws "window is not defined". Right: View.onMount or SSRContext.onClient.

  6. Request state in module-level signals on a server. Symptom: one user's data appears in another user's HTML. Right: per-request rendering with SSRState.clear(); keep request data in components or pass it as props.

  7. Hydrating "app" after renderDocument. Symptom: hydrateById finds the element but the markup does not line up, or finds nothing. Right: renderDocument uses <div id="root">; hydrate "root".

Edge cases

  • Router.initSSR mutates the shared router singleton; render routes sequentially in one process (not concurrently with interleaved awaits).
  • Hydration.hydrateById does nothing when the id is missing; a typo produces a silently non-interactive page. Pass ~options={onHydrated: () => …} to log success during development.
  • A page that a crawler fetches from a client-only SPA is empty (<div id="app"></div>); prerender pages that must be indexed.
  • GitHub Pages serves dist/404.html with status 404 for unknown paths; prerendered route/index.html files avoid the 404 status.
  • Resources render Pending in prerendered HTML; data then loads in the browser after hydration unless transferred with SSRState.

SSR and hydration

This page is the SSR deployment procedure; the full rendering model (markers, renderId, SSRState codecs) is in /docs/advanced/ssr. Key points for deployment: the server entry runs every imported module's top-level code in Node; the client entry must render the identical tree; transferred state must be recorded after it is final and restored (SSRState.sync) before hydrating.

Verify

  • npx rescript && npx vite build completes; dist/index.html references hashed assets under the configured base.
  • For prerendering: node scripts/prerender.mjs writes dist/<route>/index.html; each file contains the route's content (not just the empty container) and <a href> values carry the base path.
  • In the browser: reload a deep route (works with fallback or prerender); after load, clicking a Router.link changes the URL without a full reload; no hydration warnings in the console.
  • /docs/advanced/ssr — rendering, hydration markers, SSRState.
  • /docs/learn/routing — routes, links, basePath.
  • /docs/guides/fetching-data — server data transfer timing.
  • /docs/guides/project-structure — entry files and module rules.