Deploying
Build for production, host as a static site or under a subpath, and prerender pages to HTML.
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.res2Router.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/_redirectsfile containing/* /index.html 200. - Vercel: add a rewrite from
/(.*)to/index.htmlinvercel.json. - GitHub Pages: there is no rewrite setting. Copy
dist/index.htmltodist/404.htmlafter 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'23export 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.res2let 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.res2Router.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.mjs2import fs from 'node:fs'3import path from 'node:path'45const routes = ['/', '/about']6const template = fs.readFileSync('dist/index.html', 'utf-8')7const { render } = await import(path.resolve('dist-server/EntryServer.res.js'))89for (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.onMountNew 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.SSRContexttells you where code runs.SSRContext.isClientandSSRContext.isServerare constants you can branch on, andSSRContext.onClient(() => ...)runs a function only in the browser, returningSomeof its result there andNoneon 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
baseand inRouter.init, and leave it out of your links. - Mounting instead of hydrating prerendered pages.
View.mountByIdrenders from scratch. UseHydration.hydrateById, which adopts the HTML that is already there. - Touching
windowat the top of a module. It runs during prerendering and crashes the build. Move it intoView.onMountorSSRContext.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
| Item | Import / entry | First stable | Changed in 7.2.0 | Needs the PPX |
|---|---|---|---|---|
Router.init, Router.initSSR (with ~basePath) | xote, xote/router | stable (all 7.x) | — | No |
SSR.renderToString, SSR.renderDocument | xote, xote/ssr | stable (all 7.x) | — | No |
Hydration.hydrate, Hydration.hydrateById | xote, xote/hydration | stable (all 7.x) | — | No |
SSRState | xote, xote/ssr-state | 7.0.0 | — | No |
SSRContext (isServer, isClient, onClient, onServer, match) | xote, xote/ssr-context | stable (all 7.x) | — | No |
View.onMount | xote | 7.2.0 (new) | — | No |
Rules
- Build order: compile ReScript (
rescript), then Vite (vite build). Vite bundles the compiled.res.mjsfiles; it does not compile.res. - 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. - Base path: Vite
base(for asset URLs) andRouter.init(~basePath)(for routing) MUST name the same path.~basePathis normalised (leading slash added, trailing slash removed); Vite'sbaseshould end with/. - With a base path, route patterns and
Router.push/Router.replace/Router.linktargets stay app-relative (/about).Router.linkandRouter.Linkrenderhrefwith 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. - Server/prerender entry: call
Router.initSSR(~pathname, ())(plus~basePathwhen used;~pathnameis app-relative) beforeSSR.renderToString, for every route rendered.initSSRsets the shared router state, including resettingbasePathto"/"when omitted. - Client entry for prerendered or server-rendered HTML MUST hydrate (
Hydration.hydrateById(app, id)), not mount:View.mountByIdrenders 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. SSR.renderToStringreturns 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.renderDocumentreturns a full document and places the app inside<div id="root">; the client then hydrates"root".- One prerender process renders many routes: module-level state (signals, resources,
SSRStateregistry) persists between routes. CallSSRState.clear()per route/request and do not keep request data in module-level signals. - Resources created during a server render do not fetch (they render
Pending); data needed in the HTML must be loaded before rendering and transferred withSSRState(see the Fetching data guide). SSRContext.isServeristypeof document === 'undefined'evaluated when Xote loads. In Vite's SSR build run by Node it istrue; in the browserfalse.View.onMountnever runs on the server; in the browser it runs after hydration. Put DOM work (focus, measurement,localStorage) there or inSSRContext.onClient.- Asset URLs written as string literals in code (
"/logo.svg") are not rewritten by Vite'sbase; import the asset or prefix with Vite'simport.meta.env.BASE_URL.
API
| Name | Signature | Behaviour |
|---|---|---|
Router.init | (~basePath: string=?, unit) => unit | Browser: reads the URL, listens to history. Call once in the entry. |
Router.initSSR | (~basePath: string=?, ~pathname: string=?, ~search: string=?, ~hash: string=?, unit) => unit | Server: sets the location without browser APIs. |
SSR.renderToString | (unit => View.node, ~options: renderOptions=?) => string | App HTML with hydration markers. |
SSR.renderDocument | (~head: string=?, ~bodyAttrs: string=?, ~scripts: array<string>=?, ~styles: array<string>=?, ~stateScript: string=?, ~nonce: string=?, unit => View.node) => string | Full HTML document; app inside <div id="root">. |
Hydration.hydrateById | (unit => View.node, string, ~options: hydrateOptions=?) => unit | Adopts server markup in that element; no-op if the id is missing. |
SSRState.clear | unit => unit | Resets 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) => 'a | Environment-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.res2Router.init()3View.mountById(<App />, "app")
1npx rescript && npx vite build # output: dist/
Host fallback (pick the host's mechanism):
- Netlify:
public/_redirectscontaining/* /index.html 200. - Vercel:
vercel.jsonwith{"rewrites": [{"source": "/(.*)", "destination": "/index.html"}]}. - GitHub Pages (no rewrites): copy
dist/index.htmltodist/404.htmlafter 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.mjs2import { defineConfig } from 'vite'3export default defineConfig({ base: '/my-app/' })
1// src/Main.res2Router.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.res2let render = (url: string) => {3 Router.initSSR(~pathname=url, ())4 SSR.renderToString(() => <App />)5}
1// src/EntryClient.res2Router.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.mjs2import fs from 'node:fs'3import path from 'node:path'45const routes = ['/', '/about']6const template = fs.readFileSync('dist/index.html', 'utf-8')7const { render } = await import(path.resolve('dist-server/EntryServer.res.js'))89for (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
-
No SPA fallback. Symptom: navigating inside the app works; reloading
/aboutreturns the host's 404. Right: configure the host rewrite, or prerender. -
Base path in one place only. Wrong: Vite
base: '/my-app/'butRouter.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. -
Writing the base path into links. Wrong:
Router.link(~to="/my-app/about", …). Symptom:href="/my-app/my-app/about". Right:~to="/about". -
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"). -
Browser API at module top level. Wrong:
let width = window["innerWidth"]in a component module. Symptom:vite build --ssrsucceeds but prerendering throws "window is not defined". Right:View.onMountorSSRContext.onClient. -
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. -
Hydrating
"app"afterrenderDocument. Symptom:hydrateByIdfinds the element but the markup does not line up, or finds nothing. Right:renderDocumentuses<div id="root">; hydrate"root".
Edge cases
Router.initSSRmutates the shared router singleton; render routes sequentially in one process (not concurrently with interleaved awaits).Hydration.hydrateByIddoes 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.htmlwith status 404 for unknown paths; prerenderedroute/index.htmlfiles avoid the 404 status. - Resources render
Pendingin prerendered HTML; data then loads in the browser after hydration unless transferred withSSRState.
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 buildcompletes;dist/index.htmlreferences hashed assets under the configuredbase.- For prerendering:
node scripts/prerender.mjswritesdist/<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.linkchanges the URL without a full reload; no hydration warnings in the console.
Related
/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.