Rsbuild SSR HTML

Server-side rendering with vanilla HTML, Rsbuild, and Nitro.

app
entry-client.ts
entry-server.ts
routes
api
hello.ts
index.html
package.json
rsbuild.config.ts
tsconfig.json
import { fetch } from "nitro";

export default {
  async fetch(req: Request) {
    const { message } = (await fetch("/api/hello").then((res) => res.json())) as {
      message: string;
    };
    return /* html */ `
      <h1>${message}</h1>
      <p>Rendered on the server for <code>${new URL(req.url).pathname}</code>.</p>
      <button id="counter" disabled>Count: 0</button>
    `;
  },
};

This example renders an HTML template on the server with Rsbuild and the experimental nitro/rsbuild plugin, without a framework.

#Overview

Add the Nitro Rsbuild plugin to your Rsbuild config
Create an HTML template with a <!--ssr-outlet--> comment where server content goes
Create a server entry (app/entry-server.ts) that renders the page content
Create a client entry (app/entry-client.ts) that makes the page interactive
Add API routes for server-side data

#How It Works

Nitro detects app/entry-server.ts and adds an ssr environment to the Rsbuild app. The server entry exports an object with a fetch method, which calls the /api/hello route with Nitro's internal fetch and returns the HTML of the page.

The index.html template is the Rsbuild HTML template of the client: Rsbuild injects the client scripts, and Nitro renders the <!--ssr-outlet--> comment with the server entry for each page request.

Run rsbuild dev for development, and rsbuild build to build the client and the server into .output/.

#Learn More

Nitro  builds full-stack servers that deploy anywhere.