Skip to content

Commit

Permalink
feat: base ssr (#108)
Browse files Browse the repository at this point in the history
* Base ssr package created

* Base ssr package created

* Base files created

* Added the base Renderer and Extractor

* Added renderer on boilerplate

* Added scripts

* Connected the package with the boilerplate

* Commented out locale logic

* Files fixed

* autoformatting

* remove & ignore api output files

* handle converting element props to react equivalents

* call `hydrateRoot()` in boilerplate client

* Some cleanups

* Api output directory should be ignored

* Suspense in bun works on subsequent loads

* use default renderer export

* Fix boilerplate suspense & add docs

* merge with recent updates

* Move SSR to react domain

* formatting/notes/etc

* add note to rendererserverentrypointprops.lang

* refactor rendertopipeablestreamoptions

* updates

---------

Co-authored-by: advl <[email protected]>
  • Loading branch information
jmuzina and advl authored Jan 14, 2025
1 parent 08cae3a commit acb740c
Show file tree
Hide file tree
Showing 31 changed files with 688 additions and 29 deletions.
2 changes: 2 additions & 0 deletions .github/actions/setup-env/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ runs:
with:
bun-version: ${{ inputs.bun-version }}

# TODO setup a matrix strategy to test multiple bun/node versions

# "prepare" hook on `bun install` runs `bun run build`
- name: Install dependencies
shell: bash
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,4 @@ js/app.js.map
static/js/modules

# NX cache
.nx/
.nx/
4 changes: 2 additions & 2 deletions apps/boilerplate-react-vite/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/png" sizes="32x32" href="https://assets.ubuntu.com/v1/be7e4cc6-COF-favicon-32x32.png">
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
<script type="module" src="/src/ssr/entry-client.tsx"></script>
</body>
</html>
7 changes: 5 additions & 2 deletions apps/boilerplate-react-vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
"license": "GPL-3.0-only",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"build": "bun run build:client && bun run build:server",
"build:client": "vite build --ssrManifest --outDir dist/client",
"build:server": "vite build --ssr src/ssr/server.ts --outDir dist/server",
"serve": "bun run build && node dist/server/server.js",
"check": "bun run check:biome && bun run check:ts",
"check:fix": "bun run check:biome:fix && bun run check:ts",
"check:biome": "biome check src *.json",
Expand All @@ -16,6 +18,7 @@
},
"dependencies": {
"@canonical/styles": "^0.6.0-experimental.0",
"@canonical/react-ssr": "0.4.0-experimental.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { useState } from "react";
import canonicalLogo from "/canonical.svg";
import { Button } from "@canonical/react-ds-core";
import React, { Suspense, useState, lazy } from "react";
import canonicalLogo from "./assets/canonical.svg";
import reactLogo from "./assets/react.svg";
import "./App.css";
import "./Application.css";

import { Button } from "@canonical/react-ds-core";
const LazyButton = lazy(
() =>
new Promise((resolve) => {
// @ts-ignore
setTimeout(() => resolve(import("./LazyComponent.js")), 2000);
}),
);

function App() {
const [count, setCount] = useState(0);
Expand All @@ -25,6 +32,9 @@ function App() {
</div>
<h1>Canonical Design System</h1>
<h2>React Vite template</h2>
<Suspense fallback={"Loading..."}>
<LazyButton />
</Suspense>
<div className="card">
<Button
label={`Count: ${count}`}
Expand Down
13 changes: 13 additions & 0 deletions apps/boilerplate-react-vite/src/LazyComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Button } from "@canonical/react-ds-core";

function LazyComponent() {
return (
<Button
appearance={"positive"}
label={"Click me"}
onClick={() => alert("clicked!")}
/>
);
}

export default LazyComponent;
10 changes: 0 additions & 10 deletions apps/boilerplate-react-vite/src/main.tsx

This file was deleted.

7 changes: 7 additions & 0 deletions apps/boilerplate-react-vite/src/ssr/entry-client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { hydrateRoot } from "react-dom/client";
import "../index.css";
import Application from "../Application.js";

hydrateRoot(document.getElementById("root") as HTMLElement, <Application />);

console.log("hydrated");
27 changes: 27 additions & 0 deletions apps/boilerplate-react-vite/src/ssr/entry-server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type {
ReactServerEntrypointComponent,
RendererServerEntrypointProps,
} from "@canonical/react-ssr/renderer";
import React from "react";
import Application from "../Application.js";

const EntryServer: ReactServerEntrypointComponent<
RendererServerEntrypointProps
> = ({ lang = "en", scriptTags, linkTags }: RendererServerEntrypointProps) => {
return (
<html lang={lang}>
<head>
<title>Canonical React Vite Boilerplate</title>
{scriptTags}
{linkTags}
</head>
<body>
<div id="root">
<Application />
</div>
</body>
</html>
);
};

export default EntryServer;
9 changes: 9 additions & 0 deletions apps/boilerplate-react-vite/src/ssr/renderer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { JSXRenderer } from "@canonical/react-ssr/renderer";
import htmlString from "../../dist/client/index.html?raw";
import EntryServer from "./entry-server.js";

const Renderer = new JSXRenderer(EntryServer, {
htmlString,
});

export default Renderer.render;
18 changes: 18 additions & 0 deletions apps/boilerplate-react-vite/src/ssr/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as process from "node:process";
import { serveStream } from "@canonical/react-ssr/server";
import express from "express";
import render from "./renderer.js";

const PORT = process.env.PORT || 5173;

const app = express();

app.use("/(assets|public)", express.static("dist/client/assets"));

app.use(serveStream(render));

app.listen(PORT, () => {
console.log(`Server started on http://localhost:${PORT}/`);
});

export default app;
7 changes: 3 additions & 4 deletions apps/boilerplate-react-vite/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from "vite-tsconfig-paths";

// https://vitejs.dev/config/
export default defineConfig({
plugins: [tsconfigPaths(), react()],
plugins: [tsconfigPaths(), react()]
});
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions packages/generator-ds/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"check:ts": "tsc --noEmit"
},
"dependencies": {
"@canonical/utils": "^0.4.0-experimental.0",
"yeoman-generator": "^7.4.0"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion packages/generator-ds/src/component/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from "node:path";
import { casing } from "@canonical/utils";
import Generator, { type BaseOptions } from "yeoman-generator";
import globalContext from "../app/global-context.js";
import casing from "../utils/casing.js";

interface ComponentGeneratorAnswers {
/** The path to the component's root directory */
Expand Down
152 changes: 152 additions & 0 deletions packages/react/ssr/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# Canonical React SSR: No-Hassle Server-Side Rendering for React

This guide demonstrates how to set up server-side rendering (SSR) for React applications using `@canonical/react-ssr`. It covers everything from installation to building and handling SSR requests with client and server entry points.

## Table of Contents
1. [Installation](#installation)
2. [Quick Start](#quick-start)
- [Server-Side Entry Point](#server-side-entry-point)
- [Client-Side Entry Point](#client-side-entry-point)
- [Building Your Application](#building-your-application)
- [Server Request Handling](#server-request-handling)
- [Injecting the Client Application](#injecting-the-client-application)
3. [Customization](#customization)
- [Bootstrap Scripts](#bootstrap-scripts)

---

## Installation

First, install the `@canonical/react-ssr` package:

```bash
npm install @canonical/react-ssr
```

## Quick Start

This section walks you through setting up SSR for your React app, including creating entry points, building your app, and handling SSR requests.

### Entrypoints

You will notice that this setup encourages two entry points: one for the server, and one for the client.
The server entry point includes the full application HTML for compatibility with streams.
The client entry point includes just the application component, which is hydrated on the client.

### Server-Side Entry Point

Create a server-side entry point to wrap your application and inject the necessary scripts and links into the HTML.

```tsx
// src/ssr/entry-server.tsx
import Application from "../Application.js";
import React from "react";
import type {ReactServerEntrypointComponent, RendererServerEntrypointProps} from "@canonical/react-ssr/renderer";

// Define your server-side entry point component
const EntryServer: ReactServerEntrypointComponent<RendererServerEntrypointProps> = ({ lang = "en", scriptTags, linkTags }) => (
<html lang={lang}>
<head>
<title>Canonical React SSR</title>
{scriptTags}
{linkTags}
</head>
<body>
<div id="root">
<Application />
</div>
</body>
</html>
);

export default EntryServer;
```
This component is responsible for rendering the HTML structure and injecting the necessary script and link tags that are required for hydration on the client.

### Client-Side Entry Point
Set up client-side hydration to rehydrate your app after the SSR content has been rendered.
```tsx
// src/ssr/entry-client.tsx
import { hydrateRoot } from "react-dom/client";
import Application from "../Application.js";

// Hydrate the client-side React app after the server-rendered HTML is loaded
hydrateRoot(document.getElementById("root") as HTMLElement, <Application />);
```

### Building your application
To build your SSR React app, use a tool like Vite, Webpack, or Next.
The build process should include both client and server bundles. First, build the client-side app, then the server-side entry point.
The example below uses Vite.

```json5
// package.json
{
"scripts": {
"build": "bun run build:client && bun run build:server",
"build:client": "vite build --ssrManifest --outDir dist/client",
"build:server": "vite build --ssr src/ssr/server.ts --outDir dist/server"
}
}

```

### Server Request Handling

Once your app is built, you can set up an Express server to handle SSR requests.
See [this file](../../../apps/boilerplate-react-vite/src/ssr/server.ts) as an example.

### Injecting the Client Application

Your client-side entry point must be executed by the client upon page load to rehydrate the server-rendered app.

Example for injecting the client application into your HTML with Vite:

```html
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<!-- Inject the client-side entry point -->
<script type="module" src="/src/ssr/entry-client.tsx"></script>
</body>
</html>
```
This script will hydrate the app on the client, connecting the React app to the server-rendered HTML.

#### Customization
You can inject additional bootstrapping scripts to customize the client-side setup.
This is useful if you need more control over how the client app boots.

##### Bootstrap Scripts
You can pass custom modules, scripts, or inline script content to be executed on the client before the app is hydrated.

###### Options
- `bootstrapModules`: An array of module paths. Generates `<script type="module" src="{SCRIPT_LINK}"></script>` elements.
- `bootstrapScripts`: An array of script paths. Generates `<script type="text/javascript" src="{SCRIPT_LINK}"></script>` elements.
- `bootstrapScriptContent`: Raw script content. Generates `<script type="text/javascript">{SCRIPT_CONTENT}</script>` elements.

```ts
import { JSXRenderer } from "@canonical/react-ssr/renderer";
// Pass custom bootstrap scripts to the renderer
const Renderer = new JSXRenderer(
EntryServer,
{
htmlString,
renderToPipeableStreamOptions: {
bootstrapModules: ["src/ssr/entry-client.tsx"] // Adds the client-side entry module to the page
}
}
);
```

The `JSXRenderer` also accepts `renderToPipeableStreamOptions`, which are passed to react-dom/server`'s `renderToPipeableStream()`.

For further information, refer to [React's `renderToPipeableStream()` documentation](https://react.dev/reference/react-dom/server/renderToPipeableStream#parameters).



4 changes: 4 additions & 0 deletions packages/react/ssr/biome.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
"extends": ["@canonical/biome-config"]
}
Loading

0 comments on commit acb740c

Please sign in to comment.