react-router-hono-server 3.0.0-next.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1249 +1,820 @@
1
- # React Router v8 Hono Server
1
+ # React Router Hono Server
2
2
 
3
- <!-- ![GitHub Repo stars](https://img.shields.io/github/stars/rphlmr/react-router-hono-server?style=social)
4
- ![npm](https://img.shields.io/npm/v/open-source-stack?style=plastic)
5
- ![GitHub](https://img.shields.io/github/license/rphlmr/react-router-hono-server?style=plastic)
6
- ![npm](https://img.shields.io/npm/dy/open-source-stack?style=plastic)
7
- ![npm](https://img.shields.io/npm/dw/open-source-stack?style=plastic)
8
- ![GitHub top language](https://img.shields.io/github/languages/top/rphlmr/react-router-hono-server?style=plastic) -->
3
+ Run a React Router framework-mode application on Hono—without giving up the runtime you want.
9
4
 
10
- ## Psst!
11
- > [!IMPORTANT]
12
- > This package is only compatible with React Router v7
13
- >
14
- > You can still use the v1 with @remix-run. [Previous docs](https://github.com/rphlmr/react-router-hono-server/tree/v1.2.0)
15
- >
16
- > Migration guide from v1 [here](#migrate-from-v1)
5
+ `react-router-hono-server` provides a Vite plugin and production adapters for Node.js, Bun, Deno, Cloudflare Workers, and AWS Lambda.
17
6
 
18
- ## TLDR
19
- This package contains a helper function `createHonoServer` that enables you to create a Hono
20
- server bound to your React Router v7 app.
7
+ It gives your application one clear server boundary:
21
8
 
22
- Since the Hono server is built along with the rest of your app, you may import app modules as needed.
9
+ - React Router owns routes, loaders, actions, and rendering.
10
+ - Hono owns middleware, API routes, request context, and runtime integration.
11
+ - This package connects them and handles startup, static assets, and build output.
23
12
 
24
- It also supports Vite HMR via the `react-router-hono-server/dev` plugin (which is required
25
- for this to function).
13
+ ## Why use it?
26
14
 
27
- It presets a default Hono server config that you can [customize](#options)
15
+ - **One server API across five runtimes.** Move between runtimes without redesigning the application.
16
+ - **First-class Hono customization.** Add middleware, API endpoints, typed context, and runtime options around React Router.
17
+ - **Production and development parity.** Use the same server entry in Vite development and in the production runtime.
18
+ - **React Router features stay intact.** SSR, prerendering, SPA output, basenames, and custom build layouts remain React Router configuration.
19
+ - **Small default surface.** Start with a virtual server entry and reveal files only when customization is needed.
28
20
 
21
+ ## Contents
29
22
 
30
- > [!IMPORTANT]
31
- > Only works with React Router v7 in **ESM mode**
32
- >
33
- > Only works with **Vite**
34
- >
35
- > Only **Node**, **Bun**, **Cloudflare Workers** and **AWS Lambda** (experimental) are supported
23
+ - [Runtime matrix](#runtime-matrix)
24
+ - [Requirements and compatibility](#requirements-and-compatibility)
25
+ - [Minimal Node quick start](#minimal-node-quick-start)
26
+ - [Runtime selection](#runtime-selection)
27
+ - [Reveal and entry files](#reveal-and-entry-files)
28
+ - [Runtime guides](#runtime-guides)
29
+ - [Node.js](#nodejs)
30
+ - [Bun](#bun)
31
+ - [Deno](#deno)
32
+ - [Cloudflare Workers](#cloudflare-workers)
33
+ - [AWS Lambda](#aws-lambda)
34
+ - [Server customization](#server-customization)
35
+ - [API and exports](#api-and-exports)
36
+ - [Troubleshooting](#troubleshooting)
37
+
38
+ ## Runtime matrix
39
+
40
+ | Runtime | Development | Production | WebSockets | Static assets |
41
+ | ------------------ | ----------------------------------- | ------------------------------------ | ---------- | ------------------------------- |
42
+ | Node.js | React Router dev server | Node HTTP/HTTPS | Yes | Node filesystem |
43
+ | Bun | Bun-powered React Router dev server | `Bun.serve` | Yes | Bun filesystem |
44
+ | Deno | Deno-powered Vite dev server | `Deno.serve` | Yes | Deno filesystem |
45
+ | Cloudflare Workers | Cloudflare Vite plugin and Workerd | Worker + asset binding | Yes | Workers assets |
46
+ | AWS Lambda | React Router dev server | Lambda handler or response streaming | No | Use CloudFront/S3 in production |
47
+
48
+ Choose the runtime that matches your deployment target. Application routes and Hono configuration remain portable; runtime-specific server options stay isolated in `app/server.ts`.
49
+
50
+ ## Requirements and compatibility
51
+
52
+ ### Supported versions
36
53
 
37
- > [!TIP]
38
- > 👨‍🏫 There is some examples in the [examples](./examples) folder. I hope they will help you.
54
+ - Node.js 24.19 or newer is required for installation, builds, and the CLI.
55
+ - React 19.2, React DOM 19.2, React Router 8.3 or newer, Vite 8, and Hono 4 are supported.
56
+ - `@hono/node-server` 2 is installed with this package for Node-backed functionality; applications only need to install it directly when they import it themselves.
57
+ - Bun 1.3 or newer is required for Bun execution.
58
+ - Deno 2 is required for Deno execution.
59
+ - Cloudflare projects require the current `@cloudflare/vite-plugin`, Wrangler 4, an `ASSETS` binding, and the `nodejs_compat` compatibility flag.
60
+
61
+ > [!IMPORTANT]
62
+ > Keep the application and this package on one installation of React, React DOM, React Router, Hono, and Vite.
39
63
  >
40
- > You can use [remix-hono](https://github.com/sergiodxa/remix-hono) to add cool middleware like [`session`](https://github.com/sergiodxa/remix-hono?tab=readme-ov-file#session-management)
64
+ > Aliased or duplicated framework packages can cause invalid hooks, incompatible contexts, and build failures.
41
65
 
42
- ## Installation
66
+ ## Minimal Node quick start
43
67
 
44
- Install the following npm package.
68
+ This guide assumes you already have the default [React Router framework-mode project](https://reactrouter.com/start/framework/installation). This package adds a Hono server to that application; it does not scaffold the React Router application itself.
45
69
 
46
- > [!NOTE]
47
- > This is not a dev dependency, as it creates the Hono server used in production.
70
+ The install commands below are changes to that default project. Keep its existing `@react-router/dev` and `vite` packages for every runtime. Keep `@react-router/node` for Node and AWS, but remove it for Bun, Deno, and Cloudflare so React Router selects its Web Streams renderer. This package replaces `@react-router/serve` on every runtime.
48
71
 
49
- ```bash
50
- npm install react-router-hono-server hono @hono/node-server
72
+ The following setup creates a Node.js server. The other runtime guides use the same structure with a different adapter.
51
73
 
52
- # For Bun you can install @hono/node-server as a dev dependency
53
- bun install -D @hono/node-server
74
+ ### 1. Install the packages
54
75
 
55
- # For Cloudflare Workers, add the following
56
- npm install -D miniflare wrangler
76
+ ```sh
77
+ pnpm remove @react-router/serve
78
+ pnpm add react-router-hono-server hono
57
79
  ```
58
80
 
59
- > [!TIP]
60
- > If you use `pnpm`, and want to use some imports from `hono`, you may need to install `hono` manually or create a `.npmrc` file in your project with the following content:
61
- >
62
- > ```
63
- > public-hoist-pattern[]=hono
64
- > ```
81
+ ### 2. Add the Vite plugin
82
+
83
+ Create `vite.config.ts`. The Hono server plugin must come before `reactRouter()`.
65
84
 
66
- ## Easy mode
67
- In your `vite.config.ts`, add the `reactRouterHonoServer` plugin.
85
+ <!-- canonical:node-vite -->
68
86
 
69
87
  ```ts
70
88
  import { reactRouter } from "@react-router/dev/vite";
71
- import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
89
+ import { reactRouterHonoServer } from "react-router-hono-server/dev";
72
90
  import { defineConfig } from "vite";
73
- import tsconfigPaths from "vite-tsconfig-paths";
74
91
 
75
92
  export default defineConfig({
76
- plugins: [
77
- reactRouterHonoServer(), // add this
78
- reactRouter(),
79
- tsconfigPaths()
80
- ],
93
+ plugins: [reactRouterHonoServer(), reactRouter()],
81
94
  });
82
95
  ```
83
- **That's all!**
84
96
 
85
- Wait, what?
97
+ ### 3. Create the server entry
86
98
 
87
- For really simple apps, that's all you need to do. Behind the hood, it will create a virtual module with a default Hono server.
88
- When building for production, it will create the server file at `build/server/index.js` and import your React Router app from `virtual:react-router/server-build` module (replacing it with the real file located in `build/server/assets/server-build-[hash].js`).
99
+ Create `app/server.ts`:
89
100
 
90
- ## Configuration
91
- Ok, by default it works, but you may want to customize the server and use some middleware.
101
+ <!-- canonical:node-server -->
92
102
 
93
- > [!IMPORTANT]
94
- > Until you define your own `serverEntryPoint`, the file name `${appDirectory}/server.ts` and the folder name `${appDirectory}/server` are reserved words.
95
- >
96
- > `reactRouterHonoServer` plugin is looking for them to find your server file.
103
+ ```ts
104
+ import { createHonoServer } from "react-router-hono-server/node";
97
105
 
106
+ export default await createHonoServer();
107
+ ```
98
108
 
99
- ### Add the Vite plugin
100
- > [!NOTE]
101
- > It uses the `reactRouter` plugin to build your app and will automatically load its config.
109
+ ### 4. Add package scripts
102
110
 
103
- #### Node
104
- > [!TIP]
105
- > Check this [example](./examples/node/simple/) to see how to use it.
111
+ Use these scripts in `package.json`:
106
112
 
107
- ```ts
108
- // vite.config.ts
109
- import { reactRouter } from "@react-router/dev/vite";
110
- import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
111
- import { defineConfig } from "vite";
112
- import tsconfigPaths from "vite-tsconfig-paths";
113
+ <!-- canonical:node-scripts -->
113
114
 
114
- export default defineConfig({
115
- plugins: [
116
- reactRouterHonoServer(), // add this
117
- reactRouter(),
118
- tsconfigPaths()
119
- ],
120
- });
115
+ ```json
116
+ {
117
+ "scripts": {
118
+ "build": "react-router build",
119
+ "dev": "react-router dev",
120
+ "start": "node ./build/server/index.js",
121
+ "typecheck": "react-router typegen && tsc --noEmit"
122
+ }
123
+ }
124
+ ```
125
+
126
+ ### 5. Run the application
127
+
128
+ ```sh
129
+ # Development
130
+ pnpm dev
131
+
132
+ # Production
133
+ pnpm build
134
+ pnpm start
121
135
  ```
122
136
 
123
- #### Bun
124
- > [!TIP]
125
- > Check this [example](./examples/bun/simple/) to see how to use it.
137
+ ## Runtime selection
138
+
139
+ The runtime is selected in two places:
140
+
141
+ 1. Set `runtime` in `reactRouterHonoServer()`.
142
+ 2. Import the matching adapter from the server entry.
143
+
144
+ | Runtime | Plugin option | Server import |
145
+ | ---------- | ----------------- | ------------------------------------- |
146
+ | Node.js | omitted or `node` | `react-router-hono-server/node` |
147
+ | Bun | `bun` | `react-router-hono-server/bun` |
148
+ | Deno | `deno` | `react-router-hono-server/deno` |
149
+ | Cloudflare | `cloudflare` | `react-router-hono-server/cloudflare` |
150
+ | AWS Lambda | `aws` | `react-router-hono-server/aws-lambda` |
126
151
 
127
152
  > [!IMPORTANT]
128
- > React 19 and `bun --bun` flag should work with the same `entry.server.tsx` file as Node. Check [Using `bun --bun` flag?](#using-bun---bun-flag)
129
- > Check this [example](./examples/bun/simple-bun-runtime/) to see how to use it.
153
+ > The plugin must precede `reactRouter()`. On Cloudflare, `cloudflare()` must precede both plugins.
130
154
 
131
- ```ts
132
- // vite.config.ts
133
- import { reactRouter } from "@react-router/dev/vite";
134
- import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
135
- import { defineConfig } from "vite";
136
- import tsconfigPaths from "vite-tsconfig-paths";
155
+ ## Reveal and entry files
137
156
 
138
- export default defineConfig({
139
- plugins: [
140
- reactRouterHonoServer({ runtime: "bun"} ), // add this
141
- reactRouter(),
142
- tsconfigPaths()
143
- ],
144
- });
145
- ```
157
+ React Router and this package each provide a default entry file. These entries operate at different layers and solve different problems.
146
158
 
147
- ##### Using `bun --bun` flag?
148
- > [!TIP]
149
- > Check this [example](./examples/bun/simple-bun-runtime/) to see how to use it.
159
+ | Entry | Owned by | Responsibility |
160
+ | ---------------------- | -------------------------- | ---------------------------------------------------------------------- |
161
+ | `app/server.ts` | `react-router-hono-server` | Hono middleware, API routes, load context, assets, and runtime startup |
162
+ | `app/entry.server.tsx` | React Router | Rendering a matched React Router request into a response |
163
+ | `app/entry.client.tsx` | React Router | Browser hydration |
150
164
 
151
- If you are using the [`bun --bun` flag](https://bun.sh/docs/cli/run#bun), you need to have the same `entry.server.tsx` file as Node.
165
+ Reveal only the entry you need to customize.
152
166
 
153
- When building for production, at least for React 19, it uses a special `react-dom/server.bun` import with only the `renderToReadableStream` function available.
167
+ ### Hono server entry
154
168
 
155
- React Router Hono Server vite plugin will alias that to `react-dom/server.node`
169
+ Without `app/server.ts` or `app/server/index.ts`, the plugin supplies a virtual Hono server with default options.
156
170
 
171
+ Reveal the Hono entry when you need any of the following:
157
172
 
158
- ```ts
159
- import { PassThrough } from "node:stream";
160
-
161
- import type { AppLoadContext, EntryContext } from "react-router";
162
- import { createReadableStreamFromReadable } from "@react-router/node";
163
- import { ServerRouter } from "react-router";
164
- import { isbot } from "isbot";
165
- import type { RenderToPipeableStreamOptions } from "react-dom/server";
166
- import { renderToPipeableStream } from "react-dom/server";
167
-
168
- export const streamTimeout = 5_000;
169
-
170
- export default function handleRequest(
171
- request: Request,
172
- responseStatusCode: number,
173
- responseHeaders: Headers,
174
- routerContext: EntryContext,
175
- loadContext: AppLoadContext,
176
- // If you have middleware enabled:
177
- // loadContext: unstable_RouterContextProvider
178
- ) {
179
- return new Promise((resolve, reject) => {
180
- let shellRendered = false;
181
- let userAgent = request.headers.get("user-agent");
182
-
183
- // Ensure requests from bots and SPA Mode renders wait for all content to load before responding
184
- // https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation
185
- let readyOption: keyof RenderToPipeableStreamOptions =
186
- (userAgent && isbot(userAgent)) || routerContext.isSpaMode
187
- ? "onAllReady"
188
- : "onShellReady";
189
-
190
- const { pipe, abort } = renderToPipeableStream(
191
- <ServerRouter context={routerContext} url={request.url} />,
192
- {
193
- [readyOption]() {
194
- shellRendered = true;
195
- const body = new PassThrough();
196
- const stream = createReadableStreamFromReadable(body);
197
-
198
- responseHeaders.set("Content-Type", "text/html");
199
-
200
- resolve(
201
- new Response(stream, {
202
- headers: responseHeaders,
203
- status: responseStatusCode,
204
- }),
205
- );
206
-
207
- pipe(body);
208
- },
209
- onShellError(error: unknown) {
210
- reject(error);
211
- },
212
- onError(error: unknown) {
213
- responseStatusCode = 500;
214
- // Log streaming rendering errors from inside the shell. Don't log
215
- // errors encountered during initial shell rendering since they'll
216
- // reject and get logged in handleDocumentRequest.
217
- if (shellRendered) {
218
- console.error(error);
219
- }
220
- },
221
- },
222
- );
173
+ - Hono middleware or API routes
174
+ - A React Router load context
175
+ - WebSockets
176
+ - Static-file configuration
177
+ - Runtime-specific server options
223
178
 
224
- // Abort the rendering stream after the `streamTimeout` so it has time to
225
- // flush down the rejected boundaries
226
- setTimeout(abort, streamTimeout + 1000);
227
- });
228
- }
179
+ Create `app/server.ts`:
180
+
181
+ ```sh
182
+ npx react-router-hono-server reveal file
229
183
  ```
230
184
 
231
- #### Cloudflare Workers
232
- > [!TIP]
233
- > Check this [example](./examples/cloudflare/simple/) to see how to use it.
185
+ Use the folder form when the server has colocated modules:
234
186
 
235
- > [!IMPORTANT]
236
- > You need to add the `cloudflareDevProxy` plugin to use the Cloudflare Workers runtime on dev.
187
+ ```sh
188
+ npx react-router-hono-server reveal folder
189
+ ```
237
190
 
191
+ The CLI infers the runtime from `vite.config.ts`. If it cannot find a runtime option, it generates a Node.js entry.
238
192
 
239
- ```ts
240
- // vite.config.ts
241
- import { reactRouter } from "@react-router/dev/vite";
242
- import { cloudflareDevProxy } from "@react-router/dev/vite/cloudflare"; // add this
243
- import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
244
- import { defineConfig } from "vite";
245
- import tsconfigPaths from "vite-tsconfig-paths";
193
+ > [!WARNING]
194
+ > Run the command from the project root. The reveal command overwrites its target, so do not run it over an entry you have already customized.
246
195
 
247
- export default defineConfig({
248
- plugins: [
249
- cloudflareDevProxy(),
250
- reactRouterHonoServer({ runtime: "cloudflare"} ), // add this
251
- reactRouter(),
252
- tsconfigPaths()
253
- ],
254
- });
196
+ ### React Router rendering entries
197
+
198
+ React Router supplies hidden client and server rendering entries. It selects the server renderer from the application's dependencies:
199
+
200
+ - Applications with `@react-router/node`, `@react-router/express`, or `@react-router/serve` use the Node streaming entry.
201
+ - Applications without those packages use the Web Streams entry.
202
+ - A custom `app/entry.server.tsx` always takes precedence.
203
+
204
+ Reveal the entries only when the application needs custom hydration or SSR behavior:
205
+
206
+ ```sh
207
+ npx react-router reveal
255
208
  ```
256
209
 
257
- ##### React 19
258
- > [!IMPORTANT]
259
- > Check this [example](./examples/cloudflare/simple-19/) to see how to use it.
210
+ The command generates both `app/entry.client.tsx` and `app/entry.server.tsx`.
211
+
212
+ See the [React Router reveal documentation](https://reactrouter.com/api/other-api/dev#react-router-reveal) for the generated files.
213
+
214
+ ### Optional React Router future flags
260
215
 
261
- > [!TIP]
262
- > You may need to add the `force_react_19` flag to the `reactRouterHonoServer` plugin config.
216
+ React Router 8.3 has no stable future flags. Its two unstable flags are optional and belong in `react-router.config.ts`; `reactRouterHonoServer()` does not duplicate or enable them:
263
217
 
264
218
  ```ts
265
- // vite.config.ts
266
- reactRouterHonoServer({ runtime: "cloudflare", flag: { force_react_19: true } }), // add this
219
+ import type { Config } from "@react-router/dev/config";
220
+
221
+ export default {
222
+ future: {
223
+ unstable_enableNodeReadableStream: true,
224
+ unstable_optimizeDeps: true,
225
+ },
226
+ } satisfies Config;
267
227
  ```
268
228
 
269
- #### AWS Lambda
270
- > [!TIP]
271
- > AWS shares the same runtime as Node.
272
- <!-- > Check this [example](./examples/node/simple/) to see how to use it. -->
229
+ - `unstable_enableNodeReadableStream` makes React Router use its Web Streams default entry on Node. It has no effect when `app/entry.server.tsx` exists.
230
+ - `unstable_optimizeDeps` adds the client entry and route modules to Vite's dependency optimizer in development. If it causes optimization issues, remove the flag and restart the dev server.
273
231
 
274
- ```ts
275
- // vite.config.ts
276
- import { reactRouter } from "@react-router/dev/vite";
277
- import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
278
- import { defineConfig } from "vite";
279
- import tsconfigPaths from "vite-tsconfig-paths";
232
+ These flags are experimental and may change in React Router minor releases. See React Router's [future changes guide](https://reactrouter.com/upgrading/future) and [changelog](https://reactrouter.com/changelog).
280
233
 
281
- export default defineConfig({
282
- plugins: [
283
- reactRouterHonoServer({ runtime: "aws", dev: { export: "handler" } }), // add this
284
- reactRouter(),
285
- tsconfigPaths()
286
- ],
287
- });
234
+ ## Runtime guides
235
+
236
+ ### Node.js
237
+
238
+ Node.js is the default runtime and the shortest path to production. Follow the [minimal Node quick start](#minimal-node-quick-start); no runtime option is required.
239
+
240
+ #### Node.js runtime notes
241
+
242
+ - React Router's default Node rendering entry is compatible.
243
+ - Set the listening port with `PORT` or the `port` server option.
244
+ - Use `hostname` to control the listening interface.
245
+ - Advanced options include `listeningListener`, `onServe`, `customNodeServer`, and `overrideGlobalObjects`.
246
+ - Static-file customization and WebSockets are supported.
247
+
248
+ ### Bun
249
+
250
+ #### Install
251
+
252
+ ```sh
253
+ bun remove @react-router/node @react-router/serve
254
+ bun add react-router-hono-server hono
255
+ bun add -d @types/bun
288
256
  ```
289
257
 
290
- #### Deno
291
- > [!TIP]
292
- > Check this [example](./examples/deno/simple/) to see how to use it.
258
+ #### Configure Vite
259
+
260
+ Create `vite.config.ts` and select the Bun runtime:
261
+
262
+ <!-- canonical:bun-vite -->
293
263
 
294
264
  ```ts
295
- // vite.config.ts
296
265
  import { reactRouter } from "@react-router/dev/vite";
297
- import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
266
+ import { reactRouterHonoServer } from "react-router-hono-server/dev";
298
267
  import { defineConfig } from "vite";
299
- import tsconfigPaths from "vite-tsconfig-paths";
300
268
 
301
269
  export default defineConfig({
302
- plugins: [
303
- reactRouterHonoServer({ runtime: "deno" }), // add this
304
- reactRouter(),
305
- tsconfigPaths()
306
- ],
270
+ plugins: [reactRouterHonoServer({ runtime: "bun" }), reactRouter()],
307
271
  });
308
272
  ```
309
273
 
310
- ### Create the server
311
- > [!TIP]
312
- > You can use the CLI to create the server file for you.
313
- >
314
- > ```bash
315
- > npx react-router-hono-server reveal file
316
- > ```
274
+ #### Create the server entry
317
275
 
318
- In your `app` folder, create a file named `server.ts` and export **as default** the server created by `createHonoServer`.
276
+ Create `app/server.ts`:
319
277
 
320
- ```bash
321
- touch app/server.ts
322
- ```
278
+ <!-- canonical:bun-server -->
323
279
 
324
280
  ```ts
325
- // app/server.ts
326
- import { createHonoServer } from "react-router-hono-server/node";
281
+ import { createHonoServer } from "react-router-hono-server/bun";
327
282
 
328
- export default createHonoServer({/* options */});
283
+ export default await createHonoServer();
329
284
  ```
330
285
 
331
- #### Alternative
332
- You can define your server in `app/server/index.ts`.
286
+ #### Add scripts
333
287
 
334
- > [!TIP]
335
- > You can use the CLI to create the server file for you.
336
- >
337
- > ```bash
338
- > npx react-router-hono-server reveal folder
339
- > ```
288
+ <!-- canonical:bun-scripts -->
340
289
 
341
- It is useful if you have many middleware and want to keep your server file clean.
290
+ ```json
291
+ {
292
+ "scripts": {
293
+ "build": "bunx --bun react-router build",
294
+ "dev": "bunx --bun vite",
295
+ "start": "bun ./build/server/index.js",
296
+ "typecheck": "react-router typegen && tsc --noEmit"
297
+ }
298
+ }
299
+ ```
342
300
 
343
- ```ts
344
- // app/server/index.ts
301
+ #### Run
345
302
 
346
- import { createHonoServer } from "react-router-hono-server/node";
303
+ ```sh
304
+ # Development
305
+ bun run dev
347
306
 
348
- export default createHonoServer({/* options */});
307
+ # Production
308
+ bun run build
309
+ bun run start
349
310
  ```
350
311
 
351
- #### I don't like this default
352
- No problem, you can define your files wherever you want.
312
+ #### Bun runtime notes
353
313
 
354
- Use the `serverEntryPoint` option of the Vite plugin `reactRouterHonoServer` to point to your server file.
314
+ - `bunx --bun react-router build` runs React Router and prerendering under Bun instead of following the CLI's Node.js shebang.
315
+ - `bunx --bun vite` forces Vite and its child processes to run with Bun.
316
+ - React Router automatically uses its Web Streams server entry.
317
+ - `customBunServer` forwards options to `Bun.serve`.
318
+ - Graceful shutdown, static-file customization, and WebSockets are supported.
355
319
 
320
+ ### Deno
356
321
 
357
- ### Update your package.json scripts
358
- ### Node
359
- It is not an error, you can keep the React Router defaults for `build` and `dev`!
360
- ```json
361
- "scripts": {
362
- "build": "react-router build",
363
- "dev": "react-router dev",
364
- "start": "node ./build/server/index.js",
365
- },
366
- ```
367
- ### Bun
368
- It is not an error, you can keep the React Router defaults for `build`!
369
- ```json
370
- "scripts": {
371
- "build": "react-router build",
372
- "dev": "bunx --bun vite",
373
- "start": "bun ./build/server/index.js",
374
- },
375
- ```
322
+ #### Install
376
323
 
377
- ### Cloudflare
378
- It is not an error, you can keep the React Router defaults for `build` and `dev`!
379
- ```json
380
- "scripts": {
381
- "build": "react-router build",
382
- "dev": "react-router dev",
383
- "start": "wrangler dev",
384
- },
324
+ In `package.json`, remove `@react-router/node` and `@react-router/serve`, add `react-router-hono-server` and `hono` to `dependencies`, then install with Deno:
325
+
326
+ ```sh
327
+ deno install --allow-scripts --minimum-dependency-age=0
385
328
  ```
386
329
 
387
- #### Wrangler
388
- Add a file named `wrangler.toml` at the root of your project (close to `package.json`).
330
+ #### Configure Vite
331
+
332
+ Create `vite.config.ts` and select the Deno runtime:
333
+
334
+ <!-- canonical:deno-vite -->
335
+
336
+ ```ts
337
+ import { reactRouter } from "@react-router/dev/vite";
338
+ import { reactRouterHonoServer } from "react-router-hono-server/dev";
339
+ import { defineConfig } from "vite";
389
340
 
390
- Adapt the `main` and `assets` fields based on your build output, if you changed them from the defaults.
391
- ```toml
392
- workers_dev = true
393
- name = "my-worker"
394
- compatibility_date = "2024-11-18"
395
- main = "./build/server/index.js"
396
- assets = { directory = "./build/client/" }
341
+ export default defineConfig({
342
+ plugins: [reactRouterHonoServer({ runtime: "deno" }), reactRouter()],
343
+ });
397
344
  ```
398
345
 
399
- ##### Custom assets serving
400
- You can set Cloudflare `experimental_serve_directly` and delegate assets serving to Hono, like for Node and Bun.
346
+ #### Create the server entry
401
347
 
402
- > [!TIP]
403
- > Check https://developers.cloudflare.com/workers/static-assets/binding/#experimental_serve_directly
348
+ Create `app/server.ts`:
404
349
 
405
- > [!TIP]
406
- > Check this [example](./examples/cloudflare/simple/) to see how to use it.
350
+ <!-- canonical:deno-server -->
407
351
 
408
- ```toml
409
- [assets]
410
- directory = "./build/client/"
411
- binding = "ASSETS"
412
- experimental_serve_directly = false
352
+ ```ts
353
+ import { createHonoServer } from "react-router-hono-server/deno";
354
+
355
+ export default await createHonoServer();
413
356
  ```
414
357
 
415
- ### AWS Lambda
416
- It is not an error, you can keep the React Router defaults for `build` and `dev`!
358
+ #### Add scripts
359
+
360
+ <!-- canonical:deno-scripts -->
361
+
417
362
  ```json
363
+ {
418
364
  "scripts": {
419
365
  "build": "react-router build",
420
- "dev": "react-router dev",
421
- "start": "I don't know how to start it in production mode 😅",
422
- },
366
+ "dev": "deno run --conditions=development --allow-all npm:@react-router/dev dev",
367
+ "start": "deno run --allow-all ./build/server/index.js",
368
+ "typecheck": "react-router typegen && tsc --noEmit"
369
+ }
370
+ }
423
371
  ```
424
372
 
373
+ #### Run
425
374
 
426
- ### Deno
427
- It is not an error, you can keep the React Router defaults for `build`!
428
- ```json
429
- "scripts": {
430
- "build": "react-router build",
431
- "dev": "deno run -A npm:react-router dev",
432
- "start": "deno run -A ./build/server/index.js",
433
- },
375
+ ```sh
376
+ # Development
377
+ deno task dev
378
+
379
+ # Production
380
+ deno task build
381
+ deno task start
434
382
  ```
435
383
 
436
- ## How it works
384
+ #### Deno runtime notes
437
385
 
438
- This helper works differently depending on the environment.
386
+ - The development command enables the `development` export condition required by React Router.
387
+ - `customDenoServer` forwards options to `Deno.serve`.
388
+ - Graceful shutdown and static-file customization are supported.
389
+ - WebSockets use the optional `ws` peer in Vite development and Deno's native implementation in production.
439
390
 
440
- In development, it uses [@hono/vite-dev-server](https://github.com/honojs/vite-plugins/tree/main/packages/dev-server) and loads your server and React Router app with `import('virtual:react-router/server-build')`.
441
- It can be configured in `vite.config.ts`.
391
+ ### Cloudflare Workers
442
392
 
443
- In `production`, it will create a standard node HTTP server listening at `HOST:PORT`.
444
- You can customize the production server port using the `port` option of `createHonoServer`.
393
+ #### Install
445
394
 
446
- When building for production, the Hono server is compiled as `build/server/index.js` and imports your React Router app from `assets/server-build-[hash].js`.
395
+ ```sh
396
+ pnpm remove @react-router/node @react-router/serve
397
+ pnpm add react-router-hono-server hono
398
+ pnpm add -D @cloudflare/vite-plugin @cloudflare/workers-types wrangler
399
+ ```
447
400
 
448
- To run the server in production, use `node ./build/server/index.js`.
401
+ #### Configure Vite
449
402
 
450
- That's all!
403
+ Create `vite.config.ts`. Plugin order is required:
451
404
 
452
- ### Options
405
+ <!-- canonical:cloudflare-vite -->
453
406
 
454
- #### `reactRouterHonoServer` (Vite Plugin)
455
407
  ```ts
456
- type Runtime = "node" | "bun" | "cloudflare" | "aws" | "deno";
457
-
458
- type ReactRouterHonoServerPluginOptions = {
459
- /**
460
- * The runtime to use for the server.
461
- *
462
- * Defaults to `node`.
463
- */
464
- runtime?: Runtime;
465
- /**
466
- * The path to the server file, relative to `vite.config.ts`.
467
- *
468
- * If it is a folder (`app/server`), it will look for an `index.ts` file.
469
- *
470
- * Defaults to `${appDirectory}/server[.ts | /index.ts]` if present.
471
- *
472
- * Fallback to a virtual module `virtual:react-router-hono-server/server`.
473
- */
474
- serverEntryPoint?: string;
475
- /**
476
- * The paths that are not served by the dev-server.
477
- *
478
- * Defaults include `appDirectory` content.
479
- */
480
- dev?: {
481
- /**
482
- * The paths that are not served by the dev-server.
483
- *
484
- * Defaults include `appDirectory` content.
485
- */
486
- exclude?: (string | RegExp)[];
487
- /**
488
- * The name of the export to use for the server.
489
- *
490
- * Defaults to `default`.
491
- */
492
- export?: string;
493
- };
494
- };
495
- ```
408
+ import { cloudflare } from "@cloudflare/vite-plugin";
409
+ import { reactRouter } from "@react-router/dev/vite";
410
+ import { reactRouterHonoServer } from "react-router-hono-server/dev";
411
+ import { defineConfig } from "vite";
496
412
 
497
- #### `createHonoServer`
498
- ##### All adapters
499
- ```ts
500
- export type HonoServerOptions<E extends Env = BlankEnv> = {
501
- /**
502
- * The base Hono app to use
503
- *
504
- * It will be used to mount the React Router server on the `basename` path
505
- * defined in the [React Router config](https://api.reactrouter.com/v7/types/_react_router_dev.config.Config.html)
506
- *
507
- * {@link Hono}
508
- */
509
- app?: Hono<E>;
510
- /**
511
- * Enable the default logger
512
- *
513
- * Defaults to `true`
514
- */
515
- defaultLogger?: boolean;
516
- /**
517
- * The port to start the server on
518
- *
519
- * Defaults to `process.env.PORT || 3000`
520
- */
521
- port?: number;
522
- /**
523
- * Customize the Hono server, for example, adding middleware
524
- *
525
- * It is applied after the default middleware and before the React Router middleware
526
- */
527
- configure?: <E extends Env = BlankEnv>(server: Hono<E>) => Promise<void> | void;
528
- /**
529
- * Augment the React Router AppLoadContext
530
- *
531
- * Don't forget to declare the AppLoadContext in your app, next to where you create the Hono server
532
- *
533
- * ```ts
534
- * declare module "react-router" {
535
- * interface AppLoadContext {
536
- * // Add your custom context here
537
- * whatever: string;
538
- * }
539
- * }
540
- * ```
541
- *
542
- * **To make the typing works correctly, in your `react-router.config.ts`, add future v8_middleware flag to true.**
543
- *
544
- * ```ts
545
- * import { defineConfig } from "@react-router/dev";
546
- *
547
- * export default defineConfig({
548
- * future: {
549
- * v8_middleware: true,
550
- * },
551
- * // other config options...
552
- * });
553
- * ```
554
- */
555
- getLoadContext?: (
556
- c: Context,
557
- options: {
558
- build: ServerBuild;
559
- mode: "development" | "production" | "test";
560
- }
561
- ) => Promise<AppLoadContext> | AppLoadContext;
562
- /**
563
- * Hook to add middleware that runs before any built-in middleware, including assets serving.
564
- *
565
- * You can use it to add protection middleware, for example.
566
- */
567
- beforeAll?: (app: Hono<E>) => Promise<void> | void;
568
- };
413
+ export default defineConfig({
414
+ plugins: [
415
+ cloudflare({ viteEnvironment: { name: "ssr" } }),
416
+ reactRouterHonoServer({ runtime: "cloudflare" }),
417
+ reactRouter(),
418
+ ],
419
+ });
569
420
  ```
570
421
 
571
- You can add additional Hono middleware with the `configure` function. If you do not provide a function, it will create a default Hono server.
422
+ #### Create the server entry
572
423
 
573
- If you want to set up the React Router `AppLoadContext`, pass in a function to `getLoadContext`.
424
+ Create `app/server.ts`:
574
425
 
575
- Modify the `AppLoadContext` interface used in your app.
426
+ <!-- canonical:cloudflare-server -->
576
427
 
577
- Since the Hono server is compiled in the same bundle as the rest of your React Router app, you can import app modules just like you normally would.
428
+ ```ts
429
+ import { createHonoServer } from "react-router-hono-server/cloudflare";
578
430
 
579
- ###### Example
431
+ export default await createHonoServer();
432
+ ```
580
433
 
581
- ```ts
582
- // app/server.ts
434
+ #### Configure Wrangler
583
435
 
584
- import { createHonoServer } from "react-router-hono-server/node";
436
+ Create `wrangler.jsonc`:
585
437
 
586
- /**
587
- * Declare our loaders and actions context type
588
- */
589
- declare module "react-router" {
590
- interface AppLoadContext {
591
- /**
592
- * The app version from the build assets
593
- */
594
- readonly appVersion: string;
595
- }
596
- }
438
+ <!-- canonical:cloudflare-wrangler -->
597
439
 
598
- export default createHonoServer({
599
- getLoadContext(_, { build, mode }) {
600
- const isProductionMode = mode === "production";
601
- return {
602
- appVersion: isProductionMode ? build.assets.version : "dev",
603
- };
440
+ ```jsonc
441
+ {
442
+ "$schema": "./node_modules/wrangler/config-schema.json",
443
+ "name": "my-react-router-worker",
444
+ "compatibility_date": "2026-08-11",
445
+ "compatibility_flags": ["nodejs_compat"],
446
+ "main": "./app/server.ts",
447
+ "assets": {
448
+ "directory": "./build/client",
449
+ "binding": "ASSETS",
604
450
  },
605
- });
451
+ }
606
452
  ```
607
453
 
608
- ```ts
609
- // app/routes/test.tsx
610
- import type { Route } from "./+types/test";
611
- export async function loader({ context }: Route.LoaderArgs) {
612
- // get the context provided from `getLoadContext`
613
- return { appVersion: context.appVersion }
454
+ The `ASSETS` binding connects the generated client directory to the Worker.
455
+
456
+ #### Add scripts
457
+
458
+ <!-- canonical:cloudflare-scripts -->
459
+
460
+ ```json
461
+ {
462
+ "scripts": {
463
+ "build": "react-router build",
464
+ "dev": "vite dev",
465
+ "start": "vite preview",
466
+ "typecheck": "react-router typegen && tsc --noEmit"
467
+ }
614
468
  }
615
469
  ```
616
470
 
617
- > [!TIP]
618
- > If you declare your `getLoadContext` function in a separate file, you can use the helper `createGetLoadContext` from `react-router-hono-server/{adapter}`
619
- > ```ts
620
- > import { createGetLoadContext } from "react-router-hono-server/node";
621
- >
622
- > export const getLoadContext = createGetLoadContext((c, { mode, build }) => {
623
- > const isProductionMode = mode === "production";
624
- > return {
625
- > appVersion: isProductionMode ? build.assets.version : "dev",
626
- > };
627
- > });
628
- > ```
629
-
630
- ##### Node
631
- ```ts
632
- export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
633
- /**
634
- * Listening listener (production mode only)
635
- *
636
- * It is called when the server is listening
637
- *
638
- * Defaults log the port
639
- */
640
- listeningListener?: (info: AddressInfo) => void;
641
- /**
642
- * Customize the node server (ex: using http2)
643
- *
644
- * {@link https://hono.dev/docs/getting-started/nodejs#http2}
645
- */
646
- customNodeServer?: CreateNodeServerOptions;
647
- /**
648
- * Callback executed just after `serve` from `@hono/node-server`
649
- *
650
- * **Only applied to production mode**
651
- *
652
- * For example, you can use this to bind `@hono/node-ws`'s `injectWebSocket`
653
- */
654
- onServe?: (server: ServerType) => void;
655
- /**
656
- * The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance.
657
- *
658
- * If you want this behavior, set it to `true`
659
- *
660
- * 🚨 Setting this to `true` can break `request.clone()` if you later check `instanceof Request`.
661
- *
662
- * {@link https://github.com/honojs/node-server?tab=readme-ov-file#overrideglobalobjects}
663
- *
664
- * @default false
665
- */
666
- overrideGlobalObjects?: boolean;
667
- /**
668
- * Customize the hostname of the node server
669
- */
670
- hostname?: string;
671
- /**
672
- * Customize the serve static options
673
- */
674
- serveStaticOptions?: {
675
- /**
676
- * Customize the public assets (what's in your `public` directory) serve static options.
677
- *
678
- */
679
- publicAssets?: Omit<ServeStaticOptions<E>, "root">;
680
- /**
681
- * Customize the client assets (what's in your `build/client/assets` directory - React Router) serve static options.
682
- *
683
- */
684
- clientAssets?: Omit<ServeStaticOptions<E>, "root">;
685
- };
686
- }
471
+ #### Run
472
+
473
+ ```sh
474
+ # Workerd-backed development
475
+ pnpm dev
476
+
477
+ # Local production preview
478
+ pnpm build
479
+ pnpm start
687
480
  ```
688
481
 
689
- ##### Bun
690
- ```ts
691
- export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
692
- /**
693
- * Customize the bun server
694
- *
695
- * {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
696
- */
697
- customBunServer?: Serve.Options<unknown, string>;
698
- /**
699
- * Callback executed after server has closed and all inflight requests completed,
700
- * before process exit. Only applicable in production mode.
701
- *
702
- * @example
703
- * ```ts
704
- * export default createHonoServer({
705
- * onGracefulShutdown: async () => {
706
- * await db.close();
707
- * },
708
- * });
709
- * ```
710
- */
711
- onGracefulShutdown?: () => Promise<void> | void;
712
- /**
713
- * Customize the serve static options
714
- */
715
- serveStaticOptions?: {
716
- /**
717
- * Customize the public assets (what's in your `public` directory) serve static options.
718
- *
719
- */
720
- publicAssets?: Omit<ServeStaticOptions<E>, "root">;
721
- /**
722
- * Customize the client assets (what's in your `build/client/assets` directory - React Router) serve static options.
723
- *
724
- */
725
- clientAssets?: Omit<ServeStaticOptions<E>, "root">;
726
- };
727
- }
482
+ Deploy the generated Worker with your normal Cloudflare workflow.
483
+
484
+ #### Cloudflare runtime notes
485
+
486
+ - Public files and generated client files are served through `ASSETS`.
487
+ - Missing or unsuccessful asset responses fall through to Hono and React Router.
488
+ - Prerendering and SPA mode are supported.
489
+ - With `ssr: true`, a route without a generated asset falls through to runtime SSR.
490
+ - WebSockets use Cloudflare's native `WebSocketPair` implementation in both workerd-backed development and production.
491
+
492
+ ### AWS Lambda
493
+
494
+ #### Install
495
+
496
+ ```sh
497
+ pnpm remove @react-router/serve
498
+ pnpm add react-router-hono-server hono
728
499
  ```
729
500
 
730
- ##### Cloudflare Workers
501
+ #### Configure Vite
502
+
503
+ Create `vite.config.ts` and select the AWS runtime:
504
+
505
+ <!-- canonical:aws-vite -->
506
+
731
507
  ```ts
732
- export interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {}
508
+ import { reactRouter } from "@react-router/dev/vite";
509
+ import { reactRouterHonoServer } from "react-router-hono-server/dev";
510
+ import { defineConfig } from "vite";
511
+
512
+ export default defineConfig({
513
+ plugins: [reactRouterHonoServer({ runtime: "aws" }), reactRouter()],
514
+ });
733
515
  ```
734
516
 
735
- ##### AWS Lambda
517
+ #### Create the Lambda entry
518
+
519
+ Create `app/server.ts` for the default response mode:
520
+
521
+ <!-- canonical:aws-server -->
522
+
736
523
  ```ts
737
- type InvokeMode = "default" | "stream";
738
-
739
- interface HonoAWSServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {
740
- /**
741
- * The invoke mode to use
742
- *
743
- * Defaults to `default`
744
- *
745
- * {@link https://hono.dev/docs/getting-started/aws-lambda#lambda-response-streaming}
746
- */
747
- invokeMode: InvokeMode;
748
- }
524
+ import { createHonoServer } from "react-router-hono-server/aws-lambda";
525
+
526
+ export default await createHonoServer({ invokeMode: "default" });
749
527
  ```
750
528
 
529
+ Set `invokeMode: "stream"` to use Lambda response streaming.
751
530
 
752
- ##### Deno
753
- ```ts
754
- interface HonoDenoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
755
- /**
756
- * Customize the deno server
757
- *
758
- * {@link https://docs.deno.com/api/deno/~/Deno.serve#parameters}
759
- */
760
- customDenoServer?: Deno.ServeOptions;
761
-
762
- /**
763
- * Callback executed after server has closed and all inflight requests completed,
764
- * before process exit. Only applicable in production mode.
765
- *
766
- * @example
767
- * ```ts
768
- * export default createHonoServer({
769
- * onGracefulShutdown: async () => {
770
- * await db.close();
771
- * },
772
- * });
773
- * ```
774
- */
775
-
776
- onGracefulShutdown?: () => Promise<void> | void;
777
- /**
778
- * Customize the serve static options
779
- */
780
- serveStaticOptions?: {
781
- /**
782
- * Customize the public assets (what's in your `public` directory) serve static options.
783
- *
784
- */
785
- publicAssets?: Omit<ServeStaticOptions<E>, "root">;
786
- /**
787
- * Customize the client assets (what's in your `build/client/assets` directory - React Router) serve static options.
788
- *
789
- */
790
- clientAssets?: Omit<ServeStaticOptions<E>, "root">;
791
- };
531
+ React Router's default Node rendering entry is compatible. Reveal it only when the application needs custom SSR behavior.
532
+
533
+ #### Add scripts
534
+
535
+ <!-- canonical:aws-scripts -->
536
+
537
+ ```json
538
+ {
539
+ "scripts": {
540
+ "build": "react-router build",
541
+ "dev": "react-router dev",
542
+ "typecheck": "react-router typegen && tsc --noEmit"
543
+ }
792
544
  }
793
545
  ```
794
546
 
795
- ## Middleware
547
+ #### Build and deploy
796
548
 
797
- 🚨 Redirecting from a middleware
798
- > [!IMPORTANT]
799
- > TLDR: If you encounter a `Error: Unable to decode turbo-stream response` after a redirect from your middleware, try to use `redirect` instead of `c.redirect`.
800
- >
801
- > `redirect` will use `c.redirect` for "normal" requests and a single-fetch-like response for React Router `.data` requests.
802
- >
803
- > If the next handler is a Hono middleware (ex: https://github.com/rphlmr/react-router-hono-server/discussions/56), you can use `c.redirect` as usual.
804
- >
805
- > You **have to** use the `redirect` helper to redirect from a middleware if the next handler that will receive this redirect is a React Router route.
806
- >
807
- > It returns a single-fetch-like response.
808
- >
809
- > If you use `c.redirect`, it will not work as expected and you will get a `Unable to decode turbo-stream response` error.
810
- >
811
- >```ts
812
- > import { redirect } from "react-router-hono-server/http";
813
- >```
814
- >
815
- > I'm sorry for this inconvenience, I hope it can be "fixed" in future React Router versions.
549
+ Use `pnpm dev` locally, then run `pnpm build` before packaging `build/server` for Lambda.
816
550
 
817
- Middleware are functions that are called before React Router calls your loader/action.
551
+ Your infrastructure must expose the generated default handler as the Lambda entry.
818
552
 
819
- Hono is the perfect tool for this, as it supports middleware out of the box.
553
+ #### AWS runtime notes
820
554
 
821
- See the [Hono docs](https://hono.dev/docs/guides/middleware) for more information.
555
+ - Production static files should be served by S3, CloudFront, or another asset service.
556
+ - Prerendered files are generated in `build/client`; deploy them with the static assets.
557
+ - Requests that reach Lambda continue through runtime SSR.
558
+ - Both default responses and Lambda response streaming are supported.
822
559
 
823
- You can imagine many use cases for middleware, such as authentication, protecting routes, caching, logging, etc.
560
+ ## Server customization
824
561
 
825
- See how [Shelf.nu](https://github.com/Shelf-nu/shelf.nu/blob/main/server/middleware.ts) uses them!
562
+ Create or reveal a Hono server entry before using these options:
826
563
 
827
- > [!TIP]
828
- > This lib exports one middleware `cache` (`react-router-hono-server/middleware`) that you can use to cache your responses.
564
+ ```sh
565
+ npx react-router-hono-server reveal file
566
+ ```
829
567
 
830
- ### `beforeAll`
831
- You can use the `beforeAll` option to add middleware that runs before any built-in middleware, including assets serving.
568
+ ### Hono app and middleware ordering
832
569
 
833
- You can use it to add protection middleware, for example.
570
+ Pass `app` to use an existing Hono instance. Hooks execute in this order:
834
571
 
835
- > [!TIP]
836
- > When you check the path to protect, don't forget to use `c.req.path.includes("")` to handle `.data` requests (`loader`)!
572
+ | Order | Hook or middleware | Typical use |
573
+ | ----- | ----------------------- | ------------------------------------------------------------ |
574
+ | 1 | `beforeAll(app)` | Authentication or request policy that must run before assets |
575
+ | 2 | Built-in asset handling | Public files and generated client assets |
576
+ | 3 | Built-in logger | Request logging when `defaultLogger` is enabled |
577
+ | 4 | `configure(app)` | API routes and application middleware |
578
+ | 5 | React Router handler | Loaders, actions, and rendered routes |
837
579
 
838
580
  ```ts
839
- import { reactRouterRedirect } from "react-router-hono-server/http";
581
+ import { Hono } from "hono";
840
582
  import { createHonoServer } from "react-router-hono-server/node";
841
583
 
842
- export default createHonoServer({
843
- beforeAll(app) {
844
- app.use(async (c, next) => {
845
- if (c.req.path.includes("/protected") && !c.req.header("Authorization")) {
846
- return reactRouterRedirect("/login");
847
- }
584
+ const app = new Hono();
848
585
 
849
- return next();
586
+ export default await createHonoServer({
587
+ app,
588
+ defaultLogger: false,
589
+ beforeAll(server) {
590
+ server.use("/private/*", async (c, next) => {
591
+ if (!c.req.header("authorization")) return c.text("Unauthorized", 401);
592
+ await next();
850
593
  });
851
594
  },
595
+ configure(server) {
596
+ server.get("/api/health", (c) => c.json({ ok: true }));
597
+ },
852
598
  });
853
599
  ```
854
600
 
855
- ### Using remix-hono middleware
601
+ ### Chrome DevTools automatic workspaces
856
602
 
857
- It is easy to use [remix-hono](https://github.com/sergiodxa/remix-hono) middleware with this package.
603
+ To let Chrome DevTools automatically connect to your project, create
604
+ `public/.well-known/appspecific/com.chrome.devtools.json` with your project's absolute path and a stable UUID v4:
858
605
 
859
- ```ts
860
- import { createCookieSessionStorage } from "react-router";
861
- import { createHonoServer } from "react-router-hono-server/node";
862
- import { session } from "remix-hono/session";
863
-
864
- export default createHonoServer({
865
- configure: (server) => {
866
- server.use(
867
- session({
868
- autoCommit: true,
869
- createSessionStorage() {
870
- const sessionStorage = createCookieSessionStorage({
871
- cookie: {
872
- name: "session",
873
- httpOnly: true,
874
- path: "/",
875
- sameSite: "lax",
876
- secrets: [process.env.SESSION_SECRET],
877
- secure: process.env.NODE_ENV === "production",
878
- },
879
- });
880
-
881
- return {
882
- ...sessionStorage,
883
- // If a user doesn't come back to the app within 30 days, their session will be deleted.
884
- async commitSession(session) {
885
- return sessionStorage.commitSession(session, {
886
- maxAge: 60 * 60 * 24 * 30, // 30 days
887
- });
888
- },
889
- };
890
- },
891
- })
892
- );
893
- },
894
- });
606
+ ```json
607
+ {
608
+ "workspace": {
609
+ "root": "/absolute/path/to/your/project",
610
+ "uuid": "53b029bb-c989-4dca-969b-835fecec3717"
611
+ }
612
+ }
895
613
  ```
896
614
 
897
- ### Creating custom Hono Middleware
615
+ The development server serves this file before the React Router handler. When the file is absent, the discovery request
616
+ returns a quiet `404`. See [Automatic Workspace connection in Chrome DevTools](https://developer.chrome.com/docs/devtools/automatic-workspaces)
617
+ for setup details and security considerations.
898
618
 
899
- You can create middleware using the [`createMiddleware`](https://hono.dev/docs/helpers/factory#createmiddleware) or [`createFactory`](https://hono.dev/docs/helpers/factory#createfactory) functions from `hono/factory`.
619
+ ### Typed React Router context
900
620
 
901
- Then, use them with the `configure` function of `createHonoServer`.
621
+ React Router 8 always expects `getLoadContext` to return a `RouterContextProvider`.
902
622
 
903
623
  ```ts
904
- import { createMiddleware } from "hono/factory";
624
+ import { createContext, RouterContextProvider } from "react-router";
905
625
  import { createHonoServer } from "react-router-hono-server/node";
906
626
 
907
- export default createHonoServer({
908
- configure: (server) => {
909
- server.use(
910
- createMiddleware(async (c, next) => {
911
- console.log("middleware");
912
- return next();
913
- })
914
- );
627
+ export const requestIdContext = createContext<string>();
628
+
629
+ export default await createHonoServer({
630
+ getLoadContext(c) {
631
+ const context = new RouterContextProvider();
632
+ context.set(requestIdContext, c.req.header("x-request-id") ?? crypto.randomUUID());
633
+ return context;
915
634
  },
916
635
  });
917
636
  ```
918
637
 
919
- ### Using React Router Middleware
920
- You can use React Router middleware with this package.
638
+ Each adapter also exports `createGetLoadContext` for separately declared callbacks that need contextual typing.
921
639
 
922
- > [!TIP]
923
- > Check this [example](./examples/node/simple-future-middleware/) to see how to use it.
640
+ ### WebSockets
924
641
 
925
- > [!IMPORTANT]
926
- > **To make the typing works correctly, in your `react-router.config.ts` or where you want, add future v8_middleware flag type to true.**
927
- >
928
- > ```ts
929
- > declare module "react-router" {
930
- > interface Future {
931
- > v8_middleware: true; // 👈 Enable middleware types
932
- > }
933
- > }
934
- > ```
935
- >
936
- > If you already have a custom `getLoadContext` function, you now have to return an instance of `RouterContextProvider` from it. Check this [example](./examples/node/simple-future-middleware/) for more information.
937
- >
938
- > ```ts
939
- > import { RouterContextProvider, createContext } from "react-router";
940
- > import { createHonoServer } from "react-router-hono-server/node";
941
- >
942
- > console.log("loading server");
943
- >
944
- > type GlobalAppContext = {
945
- > appVersion: string;
946
- > };
947
- >
948
- > export const globalAppContext = createContext<GlobalAppContext>();
949
- >
950
- > export default await createHonoServer({
951
- > getLoadContext(_c, { mode, build }) {
952
- > const isProductionMode = mode === "production";
953
- > const context = new RouterContextProvider();
642
+ Node, Bun, Deno, and Cloudflare Workers support the
643
+ [Hono WebSocket helper](https://hono.dev/docs/helpers/websocket) in development
644
+ and production.
645
+
646
+ > [!NOTE]
647
+ > Node always uses `@hono/node-server`.
648
+ > Bun and Deno use it only while running through Vite in development.
649
+ > Install the optional `ws` peer and its TypeScript declarations for those modes.
954
650
  >
955
- > context.set(globalAppContext, { appVersion: isProductionMode ? build.assets.version : "dev" });
651
+ > Bun and Deno production builds use their native Hono adapters.
652
+ > They do not load `ws` in production.
956
653
  >
957
- > return context;
958
- > },
959
- > });
960
- >```
961
-
962
- Then, you can use the `use` function from `react-router` to access the context in your loaders and actions.
654
+ > Cloudflare uses its native `WebSocketPair` implementation in workerd-backed
655
+ > Vite development and production, so it never requires `ws`.
963
656
 
964
- ### Using WebSockets
965
- #### Node
966
- This package has a built-in helper to use `@hono/node-ws`.
967
-
968
- When using WebSockets with the Node adapter, install `@hono/node-ws` in your app:
969
-
970
- ```bash
971
- npm install @hono/node-ws
657
+ ```sh
658
+ pnpm add ws
659
+ pnpm add -D @types/ws
972
660
  ```
973
661
 
974
- > [!TIP]
975
- > Check this [example](./examples/node/websocket/) to see how to use it.
662
+ The portable callback API exposes `upgradeWebSocket`:
976
663
 
977
664
  ```ts
978
- import type { WSContext } from "hono/ws";
979
- import { createHonoServer } from "react-router-hono-server/node";
665
+ import { createHonoServer } from "react-router-hono-server/deno";
980
666
 
981
- // Store connected clients
982
- const clients = new Set<WSContext>();
983
-
984
- export default createHonoServer({
667
+ export default await createHonoServer({
985
668
  useWebSocket: true,
986
- // 👆 Unlock this 👇 from @hono/node-ws
987
- configure: (app, { upgradeWebSocket }) => {
669
+ configure(app, { upgradeWebSocket }) {
988
670
  app.get(
989
671
  "/ws",
990
- upgradeWebSocket((c) => ({
991
- // https://hono.dev/helpers/websocket
992
- onOpen(_, ws) {
993
- console.log("New connection ⬆️");
994
- clients.add(ws);
995
- },
672
+ upgradeWebSocket(() => ({
996
673
  onMessage(event, ws) {
997
- console.log("Context", c.req.header("Cookie"));
998
- console.log("Event", event);
999
- console.log(`Message from client: ${event.data}`);
1000
- // Broadcast to all clients except sender
1001
- clients.forEach((client) => {
1002
- if (client.readyState === 1) {
1003
- client.send(`${event.data}`);
1004
- }
1005
- });
1006
- },
1007
- onClose(_, ws) {
1008
- console.log("Connection closed");
1009
- clients.delete(ws);
674
+ ws.send(`echo:${event.data}`);
1010
675
  },
1011
- }))
676
+ })),
1012
677
  );
1013
678
  },
1014
679
  });
1015
680
  ```
1016
681
 
1017
- #### Bun
1018
- This package has a built-in helper to use `hono/bun` in prod and `@hono/node-ws` in dev
682
+ Use the matching `/bun`, `/deno`, or `/cloudflare` adapter import.
1019
683
 
1020
- > [!TIP]
1021
- > Check this [example](./examples/bun/websocket/) to see how to use it.
684
+ Cloudflare's Hono helper does not support `onOpen`.
685
+ Use `onMessage`, `onClose`, and `onError` there.
1022
686
 
1023
- ```ts
1024
- import { WSContext } from "hono/ws";
1025
- import { createHonoServer } from "react-router-hono-server/bun";
687
+ The Node adapter exposes its underlying `ws.WebSocketServer` as `wss`:
1026
688
 
1027
- // Store connected clients
1028
- const clients = new Set<WSContext>();
689
+ ```ts
690
+ import { createHonoServer } from "react-router-hono-server/node";
1029
691
 
1030
- export default createHonoServer({
692
+ export default await createHonoServer({
1031
693
  useWebSocket: true,
1032
- // 👆 Unlock this 👇 from @hono/node-ws in dev, hono/bun in prod
1033
- configure(app, { upgradeWebSocket }) {
694
+ configure(app, { upgradeWebSocket, wss }) {
695
+ wss.on("connection", (socket) => {
696
+ socket.send("connected");
697
+ });
698
+
1034
699
  app.get(
1035
700
  "/ws",
1036
- upgradeWebSocket((c) => ({
1037
- // https://hono.dev/helpers/websocket
1038
- onOpen(_, ws) {
1039
- console.log("New connection 🔥");
1040
- clients.add(ws);
1041
- },
701
+ upgradeWebSocket(() => ({
1042
702
  onMessage(event, ws) {
1043
- console.log("Context", c.req.header("Cookie"));
1044
- console.log("Event", event);
1045
- console.log(`Message from client: ${event.data}`);
1046
- // Broadcast to all clients except sender
1047
- clients.forEach((client) => {
1048
- if (client.readyState === 1) {
1049
- client.send(`${event.data}`);
1050
- }
1051
- });
1052
- },
1053
- onClose(_, ws) {
1054
- console.log("Connection closed");
1055
- clients.delete(ws);
703
+ ws.send(`echo:${event.data}`);
1056
704
  },
1057
- }))
705
+ })),
1058
706
  );
1059
707
  },
1060
708
  });
1061
709
  ```
1062
710
 
1063
- #### Cloudflare Workers
1064
- Cloudflare requires a different approach to WebSockets, based on Durable Objects.
711
+ `wss` is Node-only because it is the concrete server created by the `ws` package.
712
+ Bun, Deno, and Cloudflare use runtime-native, per-connection WebSocket APIs
713
+ instead of an equivalent central `WebSocketServer`.
1065
714
 
1066
- > [!TIP]
1067
- > Check this [example](./examples/cloudflare/websocket/) to see how to use it.
715
+ The temporary `wss` used by Bun and Deno during Vite development is not exposed.
716
+ Doing so would provide an API that disappears in production.
1068
717
 
1069
- > [!IMPORTANT]
1070
- > For now, HMR is not supported in Cloudflare Workers. Will try to come back to it later.
1071
- >
1072
- > Work in progress on Cloudflare team: https://github.com/flarelabs-net/vite-plugin-cloudflare
1073
-
1074
- #### AWS
1075
- Not supported.
718
+ Node WebSockets use `@hono/node-server` 2 and coexist with Vite HMR.
719
+ Use `wss.on("connection")`, `wss.clients`, and the connection sockets' `ping()`
720
+ method for server-level connection management and heartbeat handling.
1076
721
 
1077
- ## Basename and Hono sub apps
722
+ Bun, Deno, and Cloudflare expose only `upgradeWebSocket`.
1078
723
 
1079
- > [!NOTE]
1080
- > By default, the React Router app is mounted at `/` (default `basename` value).
1081
- >
1082
- > You may not need to use this option. It's for advanced use cases.
724
+ ### Basename and prerendering
1083
725
 
1084
- > [!TIP]
1085
- > Check this [example](./examples/node/custom-mount/) to see how to use it.
726
+ Prerendering is configured by React Router in `react-router.config.ts`.
1086
727
 
1087
- You can use the `basename` option in your React Router config (`react-router.config.ts`) to mount your React Router app on a subpath.
1088
-
1089
- It will automatically mount the app on the subpath.
728
+ #### Prerender every static route
1090
729
 
1091
730
  ```ts
1092
- // react-router.config.ts
1093
731
  import type { Config } from "@react-router/dev/config";
1094
732
 
1095
733
  export default {
1096
- basename: "/app", // Now the React Router app will be mounted on /app
734
+ prerender: true,
1097
735
  } satisfies Config;
1098
736
  ```
1099
737
 
1100
- Then, you can use the `app` option in `createHonoServer` to pass your "root" Hono app. This will be used to mount the React Router app on the `basename` path.
1101
-
1102
- ```ts
1103
- import { Hono } from "hono";
1104
- import { createHonoServer } from "react-router-hono-server/node";
1105
- import { API_BASENAME, api } from "./api";
1106
- import { getLoadContext } from "./context";
1107
-
1108
- // Create a root Hono app
1109
- const app = new Hono();
738
+ Dynamic routes are not included because their parameter values are unknown.
1110
739
 
1111
- // Mount the API app at /api
1112
- app.route(API_BASENAME, api);
1113
-
1114
- export default createHonoServer({
1115
- // Pass the root Hono app to the server.
1116
- // It will be used to mount the React Router app on the `basename` defined in react-router.config.ts
1117
- app,
1118
- getLoadContext,
1119
- });
1120
- ```
1121
- > [!NOTE]
1122
- > You now have two entry points!
1123
- > - `/api` - for your API
1124
- > - `/app` - for your React Router app
1125
-
1126
- ## Pre-rendering
1127
- You should be able to use pre-rendering with this package.
1128
-
1129
- ### Node and Bun
1130
- > [!TIP]
1131
- > Check this [example](./examples/node/with-pre-render/) to see how to use it.
1132
-
1133
- > [!IMPORTANT]
1134
- > You need to add the `serverBuildFile` option to your `react-router.config.ts` file.
1135
- >
1136
- > The file path is fixed to `assets/server-build.js`.
1137
-
1138
- Add the pre-render option to your `react-router.config.ts`
740
+ #### Prerender selected routes
1139
741
 
1140
742
  ```ts
1141
743
  import type { Config } from "@react-router/dev/config";
1142
744
 
1143
745
  export default {
1144
- prerender: ["/"],
746
+ prerender: ["/", "/about", "/posts/launch"],
1145
747
  } satisfies Config;
1146
748
  ```
1147
749
 
1148
- ### Cloudflare
1149
- > [!TIP]
1150
- > Check this [example](./examples/cloudflare/with-pre-render/) to see how to use it.
750
+ Use concrete paths such as `/posts/launch` for dynamic routes. Paths are relative to the React Router basename; do not include the basename itself.
1151
751
 
1152
- Add the pre-render option to your `react-router.config.ts`
752
+ #### Discover routes asynchronously
1153
753
 
1154
754
  ```ts
1155
755
  import type { Config } from "@react-router/dev/config";
1156
756
 
1157
757
  export default {
1158
- prerender: ["/"],
758
+ prerender: {
759
+ async paths() {
760
+ return ["/", "/about"];
761
+ },
762
+ concurrency: 4,
763
+ },
1159
764
  } satisfies Config;
1160
765
  ```
1161
766
 
767
+ React Router also accepts `basename`, `appDirectory`, and `buildDirectory` in the same configuration file.
1162
768
 
1163
- ## Migrate from v1
1164
- _You should not expect any breaking changes._
769
+ #### Deployment behavior
1165
770
 
1166
- ### Install the latest version
1167
-
1168
- ```bash
1169
- npm install react-router-hono-server@latest
1170
- ```
771
+ | Configuration | Node, Bun, Deno, and Cloudflare Workers | AWS Lambda |
772
+ | ---------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
773
+ | `ssr: true` with `prerender` | Generates and serves static documents and route data.<br>Unmatched paths use runtime SSR. | Generates the same static output, but a separate AWS asset service must serve it.<br>Unmatched Lambda requests use SSR. |
774
+ | `ssr: false` | Generates static output and an SPA fallback for static hosting | Generates static output and an SPA fallback for static hosting |
1171
775
 
1172
- ### Create the server file
1173
- #### Option 1 - You previously had all your server code in `app/entry.server.tsx`
1174
- ```bash
1175
- touch app/server.ts
1176
- ```
1177
- or
1178
- ```bash
1179
- npx react-router-hono-server reveal file
1180
- ```
1181
-
1182
- #### Option 2 - You previously had your server code in a `server` folder
1183
- ```bash
1184
- mkdir app/server
1185
- touch app/server/index.ts
1186
- ```
1187
- or
1188
- ```bash
1189
- npx react-router-hono-server reveal folder
1190
- ```
1191
-
1192
- ### Move your server code
1193
- Move your previous server code to the new file you created in the previous step.
1194
-
1195
- > [!NOTE]
1196
- > You can remove the import from `react-router-hono-server/node` in your `entry.server.tsx` file and any other server code.
776
+ - With `ssr: true`, generated files are used first and unmatched routes continue to runtime SSR.
777
+ - With `ssr: false`, React Router emits static output and an SPA fallback for static hosting.
778
+ - AWS generates the same client output, but a separate asset service must serve it before requests reach Lambda.
1197
779
 
1198
- Many options are gone, `serverBuildFile` `assetsDir` and `buildDirectory`.
780
+ The integration suite covers static and dynamic paths, async discovery, concurrency, SSR and SPA fallbacks, basenames, and custom application/build directories on every adapter.
1199
781
 
1200
- We now use the Vite virtual import `virtual:react-router/server-build` to load the server build and we read the Vite config thanks to the `reactRouterHonoServer` plugin.
782
+ See React Router's [pre-rendering guide](https://reactrouter.com/how-to/pre-rendering) for the full configuration contract.
1201
783
 
1202
- > [!IMPORTANT]
1203
- > You now need to export the server created by `createHonoServer` as **default**.
1204
- >
1205
- > ```ts
1206
- > import { createHonoServer } from "react-router-hono-server/node";
1207
- >
1208
- > export default createHonoServer({/* other options */});
1209
- > ```
1210
-
1211
- ### Update your `vite.config.ts`
1212
-
1213
- > [!IMPORTANT]
1214
- > `devServer` is now `reactRouterHonoServer`.
1215
-
1216
- Many options are gone or have changed.
1217
-
1218
- `exportName` (`reactRouterHonoServer` expects a default export from your server file), `entry` is now `serverEntryPoint`. `appDirectory` is removed (read from `vite.config.ts`), and `exclude` has been moved under `dev`.
1219
-
1220
-
1221
- ##### You used `buildEnd` from `remix()` plugin or a custom `buildDirectory` option
1222
- You may know that it has been moved to `react-router.config.ts` (see [here](https://reactrouter.com/upgrading/remix#5-add-a-react-router-config) for more information).
1223
-
1224
- If you used this hook for Sentry, check this [example](./examples/node/with-sentry/react-router.config.ts) to see how to migrate.
1225
-
1226
- If you used a custom `buildDirectory` option, check this [example](./examples/node/custom-build/react-router.config.ts) to see how to migrate.
1227
-
1228
- ### Update your package.json scripts
1229
- ```json
1230
- "scripts": {
1231
- "build": "react-router build",
1232
- "dev": "react-router dev",
1233
- "start": "node ./build/server/index.js",
1234
- },
1235
- ```
784
+ The plugin reads React Router's resolved configuration and mounts the Hono-backed handler at the same basename.
1236
785
 
1237
- ## Special Thanks
786
+ ## API and exports
1238
787
 
1239
- Inspired by [remix-express-vite-plugin](https://github.com/kiliman/remix-express-vite-plugin) from [@kiliman](https://github.com/kiliman)
788
+ | Export | Purpose |
789
+ | ------------------------------ | ------------------------------------------------------------------------------------- |
790
+ | `react-router-hono-server/dev` | `reactRouterHonoServer(options)` Vite plugin |
791
+ | `/node` | Node `createHonoServer`, options, and `createGetLoadContext` |
792
+ | `/bun` | Bun `createHonoServer`, options, and `createGetLoadContext` |
793
+ | `/deno` | Deno `createHonoServer`, options, and `createGetLoadContext` |
794
+ | `/cloudflare` | Cloudflare `createHonoServer`, options, and `createGetLoadContext` |
795
+ | `/aws-lambda` | AWS handler factory, options, and `createGetLoadContext` |
796
+ | `/middleware` | `cache(seconds)` static-response middleware |
797
+ | `/http` | `redirect(c, location)`, deprecated `reactRouterRedirect(location)`, and `getPath(c)` |
798
+ | CLI | [`react-router-hono-server reveal file` or `reveal folder`](#hono-server-entry) |
1240
799
 
1241
- `remix` handler was forked from [remix-hono](https://github.com/sergiodxa/remix-hono) by [@sergiodxa](https://github.com/sergiodxa) as it is a small and simple core dependency of this library.
800
+ ### Vite plugin options
1242
801
 
1243
- I will still help maintain it.
802
+ | Option | Purpose |
803
+ | ------------------ | --------------------------------------------------------------- |
804
+ | `runtime` | Selects the production adapter; defaults to `node` |
805
+ | `serverEntryPoint` | Overrides discovery of `app/server.ts` or `app/server/index.ts` |
806
+ | `dev.exclude` | Extends the paths excluded from Hono dev-server handling |
807
+ | `dev.export` | Selects a named export from the server entry during development |
1244
808
 
1245
- ## Contributors ✨
809
+ When no server entry is discovered, the plugin supplies a virtual default server for the selected runtime.
1246
810
 
1247
- <!-- ALL-CONTRIBUTORS-LIST:END -->
811
+ ## Troubleshooting
1248
812
 
1249
- This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
813
+ | Problem | Resolution |
814
+ | ------------------------------------------- | ------------------------------------------------------------------------------------ |
815
+ | Cloudflare plugin is missing | Add `cloudflare()` before both `reactRouterHonoServer()` and `reactRouter()` |
816
+ | Invalid hook calls or incompatible contexts | Remove aliases and duplicate framework installations, then perform one clean install |
817
+ | Server entry is not discovered | Create `app/server.ts`, create `app/server/index.ts`, or set `serverEntryPoint` |
818
+ | Load context fails at runtime | Return a `RouterContextProvider`, not a plain object |
819
+ | An asset request returns application HTML | Verify `buildDirectory`; on Cloudflare, also verify the `ASSETS` binding |
820
+ | Upgrading from the previous major | Follow [MIGRATION.md](./MIGRATION.md) and complete its clean-install checklist |