Skip to content

Vite plugin

@rezejs/vite-plugin runs the Reze compiler inside Vite. It compiles client and HTML builds and the development server. It also adds file routes, request-time streaming server rendering (SSR), static site generation (SSG), and diagnostic output when you turn them on.

Register the plugin

Install @rezejs/vite-plugin and vite as development dependencies, as described in installation. Then add reze() to plugins in vite.config.ts:

import reze from "@rezejs/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [reze()],
});

With no options, the plugin compiles files whose extension appears in DEFAULT_ROUTE_EXTENSIONS: .ts, .tsx, .js, .jsx, .mts, .cts, .mjs, and .cjs. It skips files under node_modules unless the file's package declares a reze export target. See Libraries.

reze() returns one plugin when fileRoutes, ssg, and ssr are unset. It returns an array of plugins when ssg or ssr is set, and a promise of an array when fileRoutes is set. Vite accepts nested arrays and promises in plugins, so you can pass the result directly.

Options

Every option is optional. The table lists each option, its type, and its default.

OptionTypeDefaultPurpose
analyzestring[]Not setPackage names, or scope/* prefixes, whose source the compiler analyzes when no current manifest exists. See Analyze packages without a manifest.
diagnostics.jsonlstringNot setFile that receives one JSON line per diagnostic. See Write diagnostics to a file.
linksstringNot setModule specifier that exports link. The compiler passes native <a href> elements with a routable href to it.
extensionsstring[]DEFAULT_ROUTE_EXTENSIONSExtensions the transform compiles. This value replaces the default list, so spread DEFAULT_ROUTE_EXTENSIONS to add an extension.
fileRoutesfalse, true, or an options objectfalseGenerates routes from files in a directory. true uses every default. See File routes.
ssgOptions objectNot setGenerates static HTML pages. See Static site generation.
ssrOptions objectNot setBuilds a request handler that streams HTML. See Server rendering.
profile.dirstringNot setEnables the development profiling endpoint POST /__reze/profile. Its request format and stored data are internal, so this page does not document them.

Two behaviors affect which options take effect:

  • When fileRoutes is enabled and fileRoutes.links is not false, the plugin hands native <a href> elements to @rezejs/router. That replaces the top-level links value. Set fileRoutes.links to false to keep your own links module.
  • Route files use the fileRoutes extension list, not the top-level extensions default. See the fileRoutes table below.

Libraries

A library that ships Reze source can publish a manifest of its module facts. A consumer's build reads the manifest instead of analyzing the library's source, so it can use the library's module facts across the package boundary.

Publish a manifest

Give the library two things in package.json: a reze export condition that points at its source, and a reze.manifest path where the manifest file goes:

{
  "name": "@acme/ui",
  "type": "module",
  "exports": {
    ".": {
      "reze": "./src/index.ts",
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    }
  },
  "reze": {
    "manifest": "reze.json"
  }
}

The plugin adds the reze condition to the client and to the server HTML environment, on top of Vite's default conditions, so a package that exports only reze resolves in both without extra config. The HTML environment also gets reze-html ahead of it, for packages that ship a separate server build.

The reze.manifest path is relative to the package root. The plugin scans the directory that contains each reze export target. It collects .ts, .tsx, .js, .jsx, .mts, .cts, .mjs, and .cjs files, excluding .d.ts files and node_modules.

Run the reze-manifest command from the library's root. It is installed with @rezejs/vite-plugin:

pnpm exec reze-manifest

Pass a package directory to run it elsewhere: reze-manifest <packageDir>. The command writes the manifest and reports its result:

  • On success, it prints reze-manifest: wrote N module(s) to <path> to stdout, where <path> is the manifest location.
  • For each file it cannot compile, it prints reze-manifest: skipped <file>: <codes> to stderr, where <codes> lists the diagnostic codes.
  • On failure, it prints reze-manifest: <message> to stderr and exits with code 1. A missing reze.manifest field and a missing reze export condition are both failures.

The manifest is a JSON object. Its keys are package-relative paths in sorted order, with two-space indentation and a trailing newline. Regenerate it after changing the library's source.

Analyze packages without a manifest

A consumer uses one of three sources for each library module, in this order:

  1. The manifest entry, when its hash matches the current source of the file.
  2. Analysis on the fly, when the package name matches an entry in analyze.
  3. Nothing. The compiler treats the module as opaque and has no facts about its exports.

analyze takes package names and scope/* prefixes. The @acme/* entry matches every package whose name starts with @acme/:

import reze from "@rezejs/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [reze({ analyze: ["@acme/ui", "@acme/*"] })],
});

Use analyze for libraries that do not publish a manifest yet. Use a manifest for libraries you ship, so consumers do not need to analyze your source.

Stale manifests

A manifest entry whose hash no longer matches the source is ignored. During vite dev, the plugin warns once per package:

reze: manifest of "@acme/ui" is stale. Regenerate it with `reze-manifest` in that package, or add "@acme/ui" to reze({ analyze }).

Regenerate the manifest in the package, or add the package to analyze. The warning appears only in the development server.

File routes

Set fileRoutes to generate routes from files under a directory. This feature requires @rezejs/router to be installed. Without it, the plugin stops with [reze] fileRoutes needs @rezejs/router to be installed.

Enable file routes

Set fileRoutes to true for the defaults, or to an object to change them:

import reze from "@rezejs/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    reze({
      fileRoutes: {
        dir: "src/routes",
        history: "browser",
        types: "src/routes.gen.d.ts",
      },
    }),
  ],
});

The route conventions, such as layouts, parameters, route groups, and navigation, are documented in routing. The plugin only generates the modules those conventions produce. The router API reference describes the exported values.

The fileRoutes options are:

OptionTypeDefaultPurpose
dirstring"src/routes"Route directory, relative to the Vite root. A missing directory stops the build with [reze-router] routes directory not found: <dir>.
typesstring or false"src/routes.gen.d.ts"Path of the generated type file. false disables it. The plugin writes the file when the build starts and rewrites it only when its content changes.
linksbooleantruePasses native <a href> elements to @rezejs/router, which marks the active link. Set false to keep your own links module.
history"browser" or "hash""browser""browser" builds hrefs from the Vite base. "hash" prefixes hrefs with #. Static generation rejects hash routing.
extensionsstring[]Top-level extensions, or .ts, .tsx, .js, .jsxExtensions that count as route files. When the top-level extensions option is set, this default is the top-level list.
templatebooleantrueFills a new empty .tsx or .jsx route file with a starter component during vite dev. See Dev server updates.

Route files whose names start with _ or . are ignored, along with .d.ts, .test., and .spec. files.

Generated modules

The plugin provides the virtual module virtual:reze-routes. It exports:

  • routes, a table with one entry per route, each with an id, a path, a lazy load function, and optional children.
  • paths, builders that create hrefs for the routes.

The generated type file declares virtual:reze-routes and virtual:reze-routes/register. It records each route's parameters and data, the shape of every leaf href, and the router base.

The router reports conflicting files at build time. Two files for the same route fail with [reze-router] duplicate route files for "<id>": <a>, <b>. Two routes that match the same path fail with [reze-router] routes "<a>" and "<b>" both match "<path>".

Dev server updates

During vite dev, the plugin watches dir. Adding or removing a file or directory regenerates the route module and the types file. When the route module changes, the plugin invalidates it and sends a full reload to the browser. Regeneration errors go to the Vite logger as errors.

A new empty .tsx or .jsx route file gets a starter component. A page renders its pathname and types its props with RoutePropsFor and the route pattern. A file with a directory of the same name is a layout and renders children. The plugin leaves files with content, private _ files, and other extensions as they are. Set fileRoutes.template to false to turn this off.

The document

The document is the HTML page that holds the app. It is a module whose default export returns <html> with a <head> and a <body>, and one element in the body holds children:

import type { JSX } from "reze-js";

export default function Document(props: { children: JSX.Element }) {
  return (
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>My app</title>
        <link rel="stylesheet" href="/src/styles.css" />
      </head>
      <body>
        <div id="app">{props.children}</div>
      </body>
    </html>
  );
}

The compiler turns the document into HTML for the build and for the dev server. It inlines the components the document uses, wherever they come from: the document module, another source file, or a package that ships its source under the reze export condition, such as a library <Preload> that adds <link> tags. A component's props take the literal values passed where it is used, constants declared with a literal fold in, and children takes the markup between its tags, including the document's own children:

import type { JSX } from "reze-js";

function Meta(props: { name: string; content: string }) {
  return <meta name={props.name} content={props.content} />;
}

function Shell(props: { children: JSX.Element }) {
  return <main id="app">{props.children}</main>;
}

export default function Document(props: { children: JSX.Element }) {
  return (
    <html lang="en">
      <head>
        <Meta name="color-scheme" content="light dark" />
      </head>
      <body>
        <Shell>{props.children}</Shell>
      </body>
    </html>
  );
}

With ssg or ssr, a document the compiler cannot read statically, such as one with a call, a let, or a component from a package without source, still works: the plugin compiles it for the server and runs it once, at build time and at the first dev render, and reports DOCUMENT_DYNAMIC as information naming the part that made it run. A client-only build needs a static document: it compiles the document into the HTML entry, so a call, a let, or a package without source fails the build with the diagnostic and its fix. Either way the page is plain HTML, and the document's code never reaches the browser. A document that does not return <html> with a <head> and a <body> fails with DOCUMENT_SHAPE. The element that holds children is the mount root. Its id names the root, and the compiler gives it id="app" when it has none. With ssg or ssr, the plugin adds the client script itself, so the document needs no <script type="module">; a client-only app puts its entry script in the document. With ssg or ssr, a missing document uses a document like the one above without the title and the stylesheet; a client-only app without the document keeps Vite's index.html.

Every page comes from the document: the server plugin renders it with ssg or ssr, and a client-only build uses it as the HTML entry. A project that still has an index.html at the root next to the document fails with a message that asks you to move its head tags into the document.

The document's <title>, <base>, canonical link, and <meta> tags with a name, property, or http-equiv are defaults. A <Head> tag with the same key replaces one on the pages where it renders, and the default comes back on the pages where none does.

When a server-rendered page fails before its first byte is sent, the response is a 500 page built from the same document without its module scripts, with Internal Server Error inside the mount root. During vite dev the page also shows the Vite error overlay with the error, and it keeps the dev client, so saving a fix reloads the page.

Client-only apps

Without ssg or ssr, the app renders in the browser, and src/document.tsx is the page around it. The file replaces index.html: it holds the mount element and the module script that loads your entry, and the plugin never reads index.html while the document exists. A project that still has an index.html at the root fails with a message that asks you to move its tags into the document. A project without src/document.tsx keeps Vite's index.html.

The build writes one index.html in build.outDir, and the dev server answers every path that accepts text/html with the compiled document, so the browser router owns the URL. The document is compiled once per dev server and rebuilds when the document or a component it inlines changes. The document covers the shape and the static rules.

Server rendering

Set ssr to render pages when a request arrives. The build produces a server entry that exports handler(request: Request): Promise<Response>. The handler streams the document: the HTML for everything that is ready arrives first, and each part that was still waiting for data arrives later and replaces its placeholder.

The browser runs only the components that need it. The compiler marks a component as an island when it contains a native event handler, a ref, an effect call, or useBeforeLeave. The server sends such a component with its props, and the browser renders it in place of the server HTML. A component with none of these never loads in the browser. Islands covers the island attribute, which lets you choose when a component loads.

The children of an island stay the server HTML of the component that passed them, and the islands among them run on their own. They still read the context that the island provides around children, on the server and in the browser, so the parts of a widget such as <Menu.Root><Menu.Trigger /></Menu.Root> can each be an island. An island inside children loads its module at once and renders after the enclosing island has rendered children.

Configure server rendering

import reze from "@rezejs/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    reze({
      ssr: {
        document: "src/document.tsx",
        timeoutMs: 30000,
        outDir: "dist/server",
      },
    }),
  ],
});

ssr: true takes every default. The pages are the file routes, so ssr turns fileRoutes on when it is not set and fails with fileRoutes: false. The ssr options are:

OptionTypeDefaultPurpose
documentstring"src/document.tsx"The page around the app. See The document.
timeoutMsnumber30000Time one request has to finish rendering, in milliseconds. The value must be finite and greater than zero.
outDirstring"dist/server"Directory that receives the server bundle. It is relative to the Vite root. Keep it outside the directory you serve to browsers.
devContext(request: Request) => unknownNoneBase router context for each request that the vite dev server renders. Pass the function your server uses for handler, so dev and production see the same values. See Pass request values to routes.

When you set both ssr and ssg, they must use the same document. Otherwise the plugin fails with [reze] ssg and ssr must use the same document.

Build output

vite build renders the HTML environment, builds the client, and then writes two directories:

  • The client output, in build.outDir (dist/client when ssr is set and build.outDir is not), serves from your static host. It also contains reze-assets.json. See Work with a service worker.
  • The server output, in ssr.outDir (dist/server by default), contains entry.js, which exports handler, and the files it imports. Run it with any runtime that provides the web Request and Response. The two directories must not overlap: the server directory is replaced on every build, and the client directory is served to browsers. The build fails with [reze] ssr.outDir ... overlaps build.outDir otherwise.

The client and the server must come from the same build. The server writes a build ID into every document, and a page that navigates to a document with a different build ID loads the document fully instead of swapping it.

Serve the handler

handler takes a web Request. It answers 302 for a route redirect, 404 with Not Found for a path that no route matches, and 500 with the document around Internal Server Error when rendering fails before the first byte. reze-js/server picks the implementation with export conditions (bun, node), not with runtime detection in code, so a runtime without a matching condition fails at import. The next sample is a fragment, because dist/server/entry.js exists only after a build:

import { serve } from "reze-js/server";

import { handler } from "../dist/server/entry.js";

await serve(handler, { port: 3000 });

serve(handler, options) resolves to { port, hostname, close() }. port defaults to 3000; pass 0 to get an ephemeral port and read the bound one from the result. On Node.js, createNodeListener(handler) from reze-js/server returns a request listener for an existing http server or a Connect middleware. Its request's signal aborts when the client disconnects, and the render stops. Serve the client output on the same origin, for example with your host's static file support in front of the handler.

Pass request values to routes

handler(request, { context }) takes an optional second argument. Its context is the base router context for that request: each layout's beforeLoad extends it, and every preload and redirect reads it. Use it for values that come from the request or the host, such as a session from a cookie or a platform binding. The next sample is a fragment, because dist/server/entry.js exists only after a build:

import { serve } from "reze-js/server";

import { handler } from "../dist/server/entry.js";
import { requestContext } from "../src/request-context";

await serve((request) => handler(request, { context: requestContext(request) }), { port: 3000 });

The dev server does not run this script, so pass the same function as ssr.devContext:

reze({ ssr: { devContext: requestContext } });

Static pages have no request, so ssg renders them with no base context.

Keep layout state across navigation

A navigation fetches the next page and replaces only the route levels whose server output changes. Each level is rendered inside a marker carrying the route id, its params, its data and its pending async work. A layout whose marker is unchanged keeps its DOM: sidebar scroll, an open menu, a playing video, focus and the state of islands inside it stay as they are. A layout whose preload returns data, or whose content is still waiting for an async component, changes and is replaced.

An element marked with persist survives even when its level is replaced. The current page's element with that key moves into the place where the next page renders an element with the same key:

<video persist="promo" src="/promo.mp4" />

The persisted element keeps its scroll, playback, form values and island state, and its old content stays. Use it for media players, drafts and other regions whose state matters more than their server output.

On a browser with the View Transitions API, the swap runs inside document.startViewTransition, so changed levels cross-fade instead of flashing. Browsers without the API, and users who prefer reduced motion, get the plain swap.

Streaming

A <Loading> boundary renders its fallback first, and the server streams the finished view when the data below it arrives. Async components describes <Loading> and <Errored>. An async component without a <Loading> above it makes the document wait, so the first byte arrives after the data does.

The streamed parts need JavaScript to apply. A browser with JavaScript off shows the <Loading> fallbacks. A page with no waiting parts is complete HTML.

An island is sent to the browser after everything inside it has settled. Until then, its server HTML is on the page and is not interactive.

The document contains no inline executable script, so a Content-Security-Policy that allows only script-src 'self' works.

Isolation between requests

Each request has its own module state. A module-level signal, computed, action, store, selector, effect, or createContext declaration is created again for each request, so one request never sees another request's values. Plain variables, such as a let that holds a number, stay shared across requests.

Because a shared variable leaks values between users, the compiler rejects a component or a route preload, beforeLoad, redirect, loader, or action that writes one with MODULE_STATE_SHARED. Declare the value with signal, store, selector, or createContext, or carry it through the route context that routing describes. A plain module variable stays legal as a build-time constant and as state that only browser event handlers write.

Development

vite (dev) serves the same streamed documents through the plugin. A change to a source file reloads the page.

Work with a service worker

Reze ships no service worker and puts nothing in the way of yours. The plugin writes reze-assets.json into the client output:

{ "buildId": "5b0c1f3c2a9d4e11", "files": ["/assets/index-DG3a1.js", "/assets/app-Bv9a2.css"] }

buildId changes whenever the client files change. files lists every emitted client file, joined with base, so a service worker can precache them. Every document carries <meta name="reze-build" content="<buildId>">, and a service worker can compare it with the manifest. Navigations between pages are ordinary fetch requests for HTML, so a worker that answers them from a cache or a network fallback works with the swap.

Server actions

server(schema, run) declares a mutation that runs on the server and is called from the browser or from a plain form. The schema comes from reze-js/schema and is the first argument; the compiler rejects a call without one, because every action is a public POST endpoint:

import { server } from "reze-js";
import * as s from "reze-js/schema";

export const createTodo = server(s.object({ title: s.string() }), async (input) => ({ id: 1, title: input.title }));

The handler receives the parsed input and the request. createTodo.call({ title }) posts JSON and resolves to the handler's result. createTodo.endpoint is the path of the endpoint; use it as a form action:

<form method="post" action={createTodo.endpoint}>
  <input name="title" />
  <input type="hidden" name="_return" value="/todos" />
  <button type="submit">Add</button>
</form>

A form submission is URL-encoded or multipart, runs the same schema and handler, and answers 303 to _return on success or to _return?_action_error=1 when the input is invalid. Without _return it redirects to /.

The builders are object, string, number, boolean, array, optional, literal, and enumOf. A form field arrives as a string, so use s.string() for it and convert in the handler, or call the action from script for typed JSON values. A schema can also be a module-level constant:

const input = s.object({ title: s.string() });
export const createTodo = server(input, async (value) => value.title);

Every action is a public endpoint. The schema checks the shape, not the caller: read the session, authorize, and apply CSRF protection to cookie-authenticated forms. A thrown error answers 500 without its message, and the endpoint rejects request bodies above 1 MiB.

An action registers when its module loads on the server. A module that a server-rendered route imports is loaded before the form or the .call() reaches the endpoint; a module that only a client route touches is not, so keep actions in a page, a layout, or a module those import.

Choose a render mode per route

A route module can pick how its page is produced:

export const route = { render: "client" };
renderWith ssgWith ssr
"static"A file at build time. This is the default.Rendered per request, because no file exists; add ssg to prerender it.
"server"Rejected: the build has no server to render it.Rendered per request.
"client"A shell file with the layout chain.A shell with the layout chain, then the route subtree renders in the browser.

"client" is the SPA corner of a mixed app. The server renders every layout above the route, with their data and head tags, and stops at the route. The browser mounts a client router at that boundary: the route and everything below it render in the browser, and links inside it stay client-side. A link that leaves the subtree loads the full document, so the server takes over again. Use it for screens that need browser-only APIs or that must not wait for a server render, while the marketing pages around them stay static.

When ssr and ssg are both set, static leaves are written at build time and server leaves are left to ssr; client leaves are written as shells. A hybrid build therefore serves its static pages from the CDN and its dynamic ones from the same handler. A route marked server in a build without ssr fails the build with a message to add ssr or set render: "static".

Static site generation

Set ssg to generate one HTML file per page at build time. The pages come from the same renderer as server rendering, run to completion: a generated page contains the final content, and the client bundle loads only the components that are islands.

Configure static generation

The minimum configuration is ssg: true. Every option has a default:

import reze from "@rezejs/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    reze({
      ssg: {
        document: "src/document.tsx",
        trailingSlash: "always",
        timeoutMs: 30000,
        paths: {
          "/todos/:id": [{ id: "1" }, { id: "2" }],
          "/docs/*rest": async () => [{ rest: ["guide", "setup"] }],
        },
      },
    }),
  ],
});

The ssg options are:

OptionTypeDefaultPurpose
documentstring"src/document.tsx"The page around the app. See The document.
trailingSlash"always" or "never""always"URL form of generated pages. "always" uses /todos/1/, and "never" uses /todos/1. Output file names do not change.
timeoutMsnumber30000Render deadline for one page, in milliseconds. The value must be finite and greater than zero. See Failures and timeouts.
pathsObject{}Parameter values for dynamic routes. See Map dynamic routes.

Pages

The plugin renders the file routes, one page per leaf route. There is no entry module: a leftover entry option fails with a message to remove it. Markup that every page shares and that never changes, such as a stylesheet link or a site header, belongs in the document. Each page is a flat file in src/routes, so src/routes/about.tsx is /about and paths.about() links to it. A layout that wraps a group of pages is a layout route, such as src/routes/blog.tsx around src/routes/blog/. Values shared with child routes come from a layout's beforeLoad, which routing describes.

Map dynamic routes

Static routes need no entry in paths. Each dynamic route needs one key, which is the route pattern, such as /todos/:id or /docs/*rest. The value is either an array of parameter records or a callback, synchronous or asynchronous, that returns that array:

  • A parameter value is a string or, for a splat such as *rest, a string array.
  • Optional parameters, such as :id?, may be omitted from a record.
  • An empty array produces no pages for that route.

The plugin stops with an error for these cases:

  • A dynamic route with no key: [reze-router] ssg.paths is missing dynamic route "<pattern>"; map it to [] to skip the leaf.
  • A static route with a key: [reze-router] ssg.paths has an entry for static route "<pattern>"; remove it, static leaves enumerate once.
  • A key that matches no route, or a parameter that the route does not declare.
  • A missing required parameter.
  • Two records that produce the same output, or the same URL after decoding.
  • A configuration that enumerates no pages at all.

Stream dynamic parts

With ssg and ssr in one build, ssg: { ppr: true } prerenders each page up to its first async boundary. The generated file contains the layouts, the settled content and the <Loading> fallbacks. It also carries a data-rz-resume script, and the browser fetches the settled parts from the same path with an x-reze-resume: 1 header. The handler renders the page again, sends only the patches for the parts below the first boundary, and the client applies them with the same stream protocol a server response uses. Pages without async work are written complete, without the resume script.

The parts before the first boundary must not depend on the request. Layout data from beforeLoad is fixed at build time, and a layout that reads a cookie would bake one visitor's value into the shared file. Keep request-dependent output below a <Loading> boundary, or leave the route on server.

ssg.ppr needs ssr; without it the build fails with a message to enable ssr. A static host serves the shell from the CDN, and only the resume request reaches the handler.

Cache async data

cache(load, { ttl, tags }) wraps an async loader and keys its result by the JSON-serializable call arguments on the server:

import { cache } from "reze-js";

const loadProfile = cache(async (id: string) => fetch(`https://api.example.test/users/${id}`).then((response) => response.json()), {
  ttl: 30_000,
  tags: (id) => [`user:${id}`],
});

A second render with the same arguments reuses the promise, including a render that runs concurrently. ttl is milliseconds; Infinity keeps the entry until it is revalidated. tags is a list or a function of the arguments. Arguments that JSON cannot represent call the loader without caching. A rejected load is dropped, so the next call retries. In the browser the loader runs directly, because the client router owns its own requests.

Call revalidateTag(tag) from the server handler to drop every entry with that tag:

import { serve } from "reze-js/server";

import { handler, revalidateTag } from "../dist/server/entry.js";

await serve(
  async (request) => {
    if (new URL(request.url).pathname === "/internal/revalidate") {
      revalidateTag("user:42");
      return new Response(null, { status: 204 });
    }
    return handler(request);
  },
  { port: 3000 },
);

The cache lives in the server process and is shared by every request, like any other server cache. Include the tenant or user id in the arguments of anything that differs per visitor.

Output layout### Output layout

Each page writes an index.html file inside a directory named after its URL. The output directory is Vite's build.outDir:

Page URLFile
/dist/index.html
/todos/1 or /todos/1/dist/todos/1/index.html

The trailingSlash option changes only the URL form. With "never", the page /todos/1 still lives at todos/1/index.html, so the host must map /todos/1 to that file. Generation fails when two pages collide after normalization, with [reze] SSG outputs collide after normalization.

When base is set, page and asset URLs include it.

Redirects

When a route redirects during rendering, the plugin writes a static document at the route's own URL. The document contains:

  • A canonical link to the target.
  • A <meta http-equiv="refresh"> tag that sends the reader to the target.
  • A visible link to the target.
  • A JSON script with the target.

A redirect target must be a generated page inside base, or an external http: or https: URL, or a protocol-relative // URL. Other schemes fail with [reze] unsupported redirect target. A target outside base fails with [reze] redirect target ... is outside the SSG base. A target that is not a generated page fails with [reze] redirect target ... is not a generated SSG page. Redirect cycles fail with [reze] redirect cycle: ....

Build and dev behavior

vite build runs three steps in order: it renders the HTML environment, then it builds the client, then it writes the pages. All pages render in one worker, and module state is isolated per page. The client bundle loads only the islands.

vite (dev) does not write pages. The development server renders each requested page with the same renderer.

Unsupported configurations

The plugin stops with an error for these settings:

  • build.watch, with [reze] ssg does not support build.watch.
  • An explicit SSR build, with build.ssr set to true or a string. The error is [reze] ssg does not support an explicit ssr build; it owns the HTML environment itself.
  • Your own bundler inputs. build.rollupOptions.input and build.rolldownOptions.input fail with [reze] ssg owns the bundler input; remove build.<key>.input from the config.
  • output.inlineDynamicImports, which fails with [reze] ssg needs preserved dynamic chunks; remove build.<key>.output.inlineDynamicImports.
  • Hash routing, with [reze] ssg does not support hash routing.
  • Library mode, with [reze] ssg does not support library mode.

A file in the public directory whose path matches a generated page also fails the build, with [reze] SSG output ... collides with a public directory file.

Failures and timeouts

A render error stops the build and names the URL of the page: [reze] SSG render of "<url>" failed: <message>.

Each page has timeoutMs to settle. A page that does not settle in time fails with an error naming its URL, such as [reze] Scope "<url>" did not settle within <ms>ms. The worker has a watchdog that fires 5 seconds after timeoutMs. When it fires, it stops the worker with [reze] SSG worker timed out after <timeoutMs>ms and was terminated. The message names timeoutMs, but the watchdog waits 5 seconds longer than that value.

A worker that exits unexpectedly fails with [reze] SSG worker exited with code <code>. A worker error fails with [reze] SSG worker failed: <message>.

The plugin generates no 404 page. Configure your host to answer unknown paths.

Preprocessors

The plugin compiles only the extensions in extensions. To compile another format, such as MDX, run its plugin before reze() and add its extension to the list. The preprocessor must emit JSX or TypeScript. The Reze transform then compiles that output.

The following fragment shows the wiring. It needs @mdx-js/rollup, which this docs project does not install:

import mdx from "@mdx-js/rollup";
import reze, { DEFAULT_ROUTE_EXTENSIONS } from "@rezejs/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    {
      ...mdx({ jsx: true, jsxImportSource: "reze-js" }),
      enforce: "pre",
    },
    reze({
      extensions: [...DEFAULT_ROUTE_EXTENSIONS, ".mdx"],
    }),
  ],
});

Put the preprocessor before reze() in plugins. Both plugins use enforce: "pre", so the array order decides which runs first.

Diagnostics and source maps

Write diagnostics to a file

When diagnostics.jsonl is set, the plugin appends one JSON object per line for every diagnostic it reports, at every severity. Relative paths resolve from the process working directory. The plugin does not clear the file, so delete it before a run when you want that run's output only.

Each line is a diagnostic object. This example shows an info diagnostic that the compiler reports when a signal is never written:

{
  "code": "SIGNAL_FOLDED",
  "severity": "info",
  "message": "`count` is never written, so it compiled to a plain constant.",
  "file": "/project/src/counter.tsx",
  "start": { "line": 3, "column": 7 },
  "end": { "line": 3, "column": 12 },
  "path": [],
  "labels": [],
  "fixes": [],
  "data": { "signal": "count" }
}

The fields are:

  • code: the diagnostic code. The compiler diagnostics section lists what each code means.
  • severity: error, warn, or info.
  • message: the diagnostic text.
  • file, start, and end: the source location. start and end have line and column.
  • path: an array of strings from the compiler.
  • labels: extra source ranges, each with start, end, and message.
  • fixes: suggested edits, each with a title and an edits array of start, end, and text.
  • data: string values the message refers to.

Records can also include docs and rendered.

Diagnostics printed by the plugin include a repair guide: line. It points to the compiler skill file for the code, in the form node_modules/@rezejs/compiler/skills/reze-compiler-diagnostics/SKILL.md#<code>, where <code> is the lowercase code. The plugin prints the line once per code in each run.

Source maps and hot updates

Source maps follow the Vite settings for each mode:

  • In vite build, the plugin emits source maps when build.sourcemap is set.
  • In vite dev, the plugin emits source maps when dev.sourcemap is true, or when it is an object whose js property is not false.

Outside production builds, the plugin passes debugNames to the compiler, which adds a name to each signal, computed, and action call for profiling.

Hot module replacement is on in the development server unless server.hmr is false.

Production hosting

Serve the contents of dist as static files. The plugin's output has these properties, which your host must support:

  • Each generated page is an index.html inside a directory. A request for /todos/1 must reach todos/1/index.html.
  • Pages navigate with a fetch for the next page's HTML, so the host must serve each generated page at its URL.
  • Generation emits no 404 page. Configure the host to answer unknown paths.

Optional: Run the packaged SSG smoke test

Maintainers of the Reze packages can run packages/vite-plugin/scripts/packaged-ssg-smoke.mjs to check the plugin as it ships. The script packs real native and JavaScript tarballs, installs them outside the workspace, typechecks, builds, and boots the fixtures in a browser. Its help text describes the same steps.

node packages/vite-plugin/scripts/packaged-ssg-smoke.mjs --help
node packages/vite-plugin/scripts/packaged-ssg-smoke.mjs --fixtures standalone-basics --browsers chromium

The flags are:

  • --vite <versions>: Vite versions to test, separated by commas. The default is 6.4.0,7.0.0,8.0.0. You can repeat the flag.
  • --browsers <engines>: browser engines, separated by commas: chromium, firefox, or webkit. The default comes from the REZE_SSG_BROWSERS environment variable, or chromium when it is unset. You can repeat the flag.
  • --fixtures <names>: fixtures to run, separated by commas. The default is all three: standalone-basics, router-full, and mdx-post. You can repeat the flag.
  • --artifacts-dir <dir>: a staged compiler package to use instead of building the compiler artifacts. The directory must contain package.json, index.js, index.d.ts, skills, and npm.
  • --keep: keep the scratch directory after the run. The default removes it.
  • -h or --help: print the help text.
  • Router API describes the router exports that the generated modules use.
  • Compiler describes the compiler options that this plugin passes through.