react-router-hono-server 2.17.0 → 2.19.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
@@ -47,15 +47,16 @@ Install the following npm package.
47
47
  > This is not a dev dependency, as it creates the Hono server used in production.
48
48
 
49
49
  ```bash
50
- npm install react-router-hono-server
50
+ npm install react-router-hono-server hono @hono/node-server
51
+
52
+ # For Bun you can install @hono/node-server as a dev dependency
53
+ bun install -D @hono/node-server
51
54
 
52
55
  # For Cloudflare Workers, add the following
53
56
  npm install -D miniflare wrangler
54
57
  ```
55
58
 
56
59
  > [!TIP]
57
- > You don't need to install `hono` as it is included in this package.
58
- >
59
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:
60
61
  >
61
62
  > ```
@@ -124,7 +125,7 @@ export default defineConfig({
124
125
  > Check this [example](./examples/bun/simple/) to see how to use it.
125
126
 
126
127
  > [!IMPORTANT]
127
- > React 19 and `bun --bun` flag require a special `entry.server.tsx` file. Check [Using `bun --bun` flag?](#using-bun---bun-flag)
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)
128
129
  > Check this [example](./examples/bun/simple-bun-runtime/) to see how to use it.
129
130
 
130
131
  ```ts
@@ -147,45 +148,82 @@ export default defineConfig({
147
148
  > [!TIP]
148
149
  > Check this [example](./examples/bun/simple-bun-runtime/) to see how to use it.
149
150
 
150
- If you are using the [`bun --bun` flag](https://bun.sh/docs/cli/run#bun), you need to have a proper `entry.server.tsx` file.
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.
152
+
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.
151
154
 
152
- When building for production, at least for React 19, it uses a special `react-dom-server.bun` import with only the `renderToReadableStream` function available.
155
+ React Router Hono Server vite plugin will alias that to `react-dom/server.node`
153
156
 
154
157
 
155
158
  ```ts
156
- import { isbot } from "isbot";
157
- import { renderToReadableStream } from "react-dom/server.bun";
159
+ import { PassThrough } from "node:stream";
160
+
158
161
  import type { AppLoadContext, EntryContext } from "react-router";
162
+ import { createReadableStreamFromReadable } from "@react-router/node";
159
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;
160
169
 
161
- export default async function handleRequest(
170
+ export default function handleRequest(
162
171
  request: Request,
163
172
  responseStatusCode: number,
164
173
  responseHeaders: Headers,
165
174
  routerContext: EntryContext,
166
- _loadContext: AppLoadContext
175
+ loadContext: AppLoadContext,
176
+ // If you have middleware enabled:
177
+ // loadContext: unstable_RouterContextProvider
167
178
  ) {
168
- let shellRendered = false;
169
- const userAgent = request.headers.get("user-agent");
170
-
171
- const body = await renderToReadableStream(<ServerRouter context={routerContext} url={request.url} />, {
172
- onError(error: unknown) {
173
- responseStatusCode = 500;
174
- if (shellRendered) {
175
- console.error(error);
176
- }
177
- },
178
- });
179
- shellRendered = true;
180
-
181
- if ((userAgent && isbot(userAgent)) || routerContext.isSpaMode) {
182
- await body.allReady;
183
- }
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
+ );
184
223
 
185
- responseHeaders.set("Content-Type", "text/html");
186
- return new Response(body, {
187
- headers: responseHeaders,
188
- status: responseStatusCode,
224
+ // Abort the rendering stream after the `streamTimeout` so it has time to
225
+ // flush down the rejected boundaries
226
+ setTimeout(abort, streamTimeout + 1000);
189
227
  });
190
228
  }
191
229
  ```
@@ -267,7 +305,7 @@ touch app/server.ts
267
305
  // app/server.ts
268
306
  import { createHonoServer } from "react-router-hono-server/node";
269
307
 
270
- export default await createHonoServer({/* options */});
308
+ export default createHonoServer({/* options */});
271
309
  ```
272
310
 
273
311
  #### Alternative
@@ -287,7 +325,7 @@ It is useful if you have many middleware and want to keep your server file clean
287
325
 
288
326
  import { createHonoServer } from "react-router-hono-server/node";
289
327
 
290
- export default await createHonoServer({/* options */});
328
+ export default createHonoServer({/* options */});
291
329
  ```
292
330
 
293
331
  #### I don't like this default
@@ -488,12 +526,6 @@ export type HonoServerOptions<E extends Env = BlankEnv> = {
488
526
 
489
527
  You can add additional Hono middleware with the `configure` function. If you do not provide a function, it will create a default Hono server.
490
528
 
491
- The `configure` function can be async. So, make sure to `await createHonoServer()`.
492
-
493
- > NB: If you import some shared code in your server file (or middleware), Vite will code split the file (your server code will be in a separate chunk, re-exported as default in `build/server/index.js`).
494
- >
495
- > In this situation, if you `await createHonoServer()` it will error with `Detected unsettled top-level await`. Just remove the `await` and it will work fine.
496
-
497
529
  If you want to set up the React Router `AppLoadContext`, pass in a function to `getLoadContext`.
498
530
 
499
531
  Modify the `AppLoadContext` interface used in your app.
@@ -519,7 +551,7 @@ declare module "react-router" {
519
551
  }
520
552
  }
521
553
 
522
- export default await createHonoServer({
554
+ export default createHonoServer({
523
555
  getLoadContext(_, { build, mode }) {
524
556
  const isProductionMode = mode === "production";
525
557
  return {
@@ -705,7 +737,7 @@ You can use it to add protection middleware, for example.
705
737
  import { reactRouterRedirect } from "react-router-hono-server/http";
706
738
  import { createHonoServer } from "react-router-hono-server/node";
707
739
 
708
- export default await createHonoServer({
740
+ export default createHonoServer({
709
741
  beforeAll(app) {
710
742
  app.use(async (c, next) => {
711
743
  if (c.req.path.includes("/protected") && !c.req.header("Authorization")) {
@@ -727,7 +759,7 @@ import { createCookieSessionStorage } from "react-router";
727
759
  import { createHonoServer } from "react-router-hono-server/node";
728
760
  import { session } from "remix-hono/session";
729
761
 
730
- export default await createHonoServer({
762
+ export default createHonoServer({
731
763
  configure: (server) => {
732
764
  server.use(
733
765
  session({
@@ -770,7 +802,7 @@ Then, use them with the `configure` function of `createHonoServer`.
770
802
  import { createMiddleware } from "hono/factory";
771
803
  import { createHonoServer } from "react-router-hono-server/node";
772
804
 
773
- export default await createHonoServer({
805
+ export default createHonoServer({
774
806
  configure: (server) => {
775
807
  server.use(
776
808
  createMiddleware(async (c, next) => {
@@ -808,7 +840,7 @@ import { createHonoServer } from "react-router-hono-server/node";
808
840
  // Store connected clients
809
841
  const clients = new Set<WSContext>();
810
842
 
811
- export default await createHonoServer({
843
+ export default createHonoServer({
812
844
  useWebSocket: true,
813
845
  // 👆 Unlock this 👇 from @hono/node-ws
814
846
  configure: (app, { upgradeWebSocket }) => {
@@ -854,7 +886,7 @@ import { createHonoServer } from "react-router-hono-server/bun";
854
886
  // Store connected clients
855
887
  const clients = new Set<WSContext>();
856
888
 
857
- export default await createHonoServer({
889
+ export default createHonoServer({
858
890
  useWebSocket: true,
859
891
  // 👆 Unlock this 👇 from @hono/node-ws in dev, hono/bun in prod
860
892
  configure(app, { upgradeWebSocket }) {
@@ -938,7 +970,7 @@ const app = new Hono();
938
970
  // Mount the API app at /api
939
971
  app.route(API_BASENAME, api);
940
972
 
941
- export default await createHonoServer({
973
+ export default createHonoServer({
942
974
  // Pass the root Hono app to the server.
943
975
  // It will be used to mount the React Router app on the `basename` defined in react-router.config.ts
944
976
  app,
@@ -1032,7 +1064,7 @@ We now use the Vite virtual import `virtual:react-router/server-build` to load t
1032
1064
  > ```ts
1033
1065
  > import { createHonoServer } from "react-router-hono-server/node";
1034
1066
  >
1035
- > export default await createHonoServer({/* other options */});
1067
+ > export default createHonoServer({/* other options */});
1036
1068
  > ```
1037
1069
 
1038
1070
  ### Update your `vite.config.ts`
@@ -4,6 +4,7 @@ import {
4
4
  createGetLoadContext,
5
5
  createWebSocket,
6
6
  getBuildMode,
7
+ importBuild,
7
8
  patchUpgradeListener
8
9
  } from "../chunk-XPXQNPY3.js";
9
10
  import {
@@ -11,13 +12,13 @@ import {
11
12
  } from "../chunk-YI5FED4X.js";
12
13
 
13
14
  // src/adapters/bun.ts
14
- import * as build from "virtual:react-router/server-build";
15
15
  import { Hono } from "hono";
16
16
  import { serveStatic } from "hono/bun";
17
17
  import { createMiddleware } from "hono/factory";
18
18
  import { logger } from "hono/logger";
19
19
  import { createRequestHandler } from "react-router";
20
20
  async function createHonoServer(options) {
21
+ const build = await importBuild();
21
22
  const basename = import.meta.env.REACT_ROUTER_HONO_SERVER_BASENAME;
22
23
  const mergedOptions = {
23
24
  ...options,
@@ -4,6 +4,7 @@ import {
4
4
  createGetLoadContext,
5
5
  createWebSocket,
6
6
  getBuildMode,
7
+ importBuild,
7
8
  patchUpgradeListener
8
9
  } from "../chunk-XPXQNPY3.js";
9
10
  import {
@@ -11,7 +12,6 @@ import {
11
12
  } from "../chunk-YI5FED4X.js";
12
13
 
13
14
  // src/adapters/node.ts
14
- import * as build from "virtual:react-router/server-build";
15
15
  import { serve } from "@hono/node-server";
16
16
  import { serveStatic } from "@hono/node-server/serve-static";
17
17
  import { Hono } from "hono";
@@ -19,6 +19,8 @@ import { createMiddleware } from "hono/factory";
19
19
  import { logger } from "hono/logger";
20
20
  import { createRequestHandler } from "react-router";
21
21
  async function createHonoServer(options) {
22
+ const startTime = Date.now();
23
+ const build = await importBuild();
22
24
  const basename = import.meta.env.REACT_ROUTER_HONO_SERVER_BASENAME;
23
25
  const mergedOptions = {
24
26
  ...options,
@@ -28,6 +30,7 @@ async function createHonoServer(options) {
28
30
  if (basename !== "/") {
29
31
  console.log(`\u{1F517} http://127.0.0.1:${info.port}${basename}`);
30
32
  }
33
+ console.log(`\u{1F3CE}\uFE0F Server started in ${Date.now() - startTime}ms`);
31
34
  }),
32
35
  port: options?.port || Number(process.env.PORT) || 3e3,
33
36
  defaultLogger: options?.defaultLogger ?? true,
package/dist/dev.js CHANGED
@@ -76,6 +76,16 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
76
76
  "react-dom/server": reactVersion >= 19 ? "react-dom/server.edge" : "react-dom/server.browser"
77
77
  };
78
78
  }
79
+ if (runtime === "bun" && pluginConfig.future.unstable_viteEnvironmentApi) {
80
+ throw new Error(
81
+ "The unstable_viteEnvironmentApi is not supported with the Bun runtime. Please disable it in your react-router.config.ts"
82
+ );
83
+ }
84
+ if (runtime === "bun" && env.command === "build") {
85
+ alias = {
86
+ "react-dom/server": "react-dom/server.node"
87
+ };
88
+ }
79
89
  const ssrConfig = {
80
90
  resolve: {
81
91
  alias
@@ -88,21 +98,25 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
88
98
  chunk.facadeModuleId = REACT_ROUTER_VIRTUAL_MODULE_ID;
89
99
  return "index.js";
90
100
  },
91
- // not invoked when target is webworker (single file output) TODO: Useless now
101
+ // not invoked when target is webworker (single file output)
92
102
  chunkFileNames: (chunk) => {
93
103
  if (chunk.name === "server-build") {
94
104
  return reactRouterBuildFile;
95
105
  }
96
106
  return "assets/[name]-[hash].js";
97
107
  },
108
+ manualChunks: runtime !== "cloudflare" ? (id) => {
109
+ if (id.includes(REACT_ROUTER_VIRTUAL_MODULE_ID)) {
110
+ return "server-build";
111
+ }
112
+ if (id.includes(pluginConfig.serverEntryPoint)) {
113
+ return "server";
114
+ }
115
+ return "chunk";
116
+ } : void 0,
98
117
  // We are doing that because we build a single file that only exports the Hono server
99
118
  // RR needs its exports for prerendering
100
- footer: (chunk) => {
101
- if (!chunk.isEntry) {
102
- return "";
103
- }
104
- return REACT_ROUTER_EXPORT;
105
- }
119
+ footer: runtime === "cloudflare" ? REACT_ROUTER_EXPORT : void 0
106
120
  }
107
121
  }
108
122
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-router-hono-server",
3
- "version": "2.17.0",
3
+ "version": "2.19.0",
4
4
  "type": "module",
5
5
  "description": "The Vite plugin you need to create a Hono server for your React Router app in less than 10 seconds.",
6
6
  "publishConfig": {
@@ -75,7 +75,7 @@
75
75
  "homepage": "https://github.com/rphlmr/react-router-hono-server#readme",
76
76
  "dependencies": {
77
77
  "@drizzle-team/brocli": "^0.11.0",
78
- "@hono/node-server": "^1.18.0",
78
+ "@hono/node-server": "^1.18.1",
79
79
  "@hono/node-ws": "^1.2.0",
80
80
  "@hono/vite-dev-server": "^0.20.0",
81
81
  "hono": "^4.7.5"
@@ -95,7 +95,7 @@
95
95
  },
96
96
  "peerDependencies": {
97
97
  "@cloudflare/workers-types": "^4.20250317.0",
98
- "@hono/node-server": "1.14.1",
98
+ "@hono/node-server": "^1.18.1",
99
99
  "@react-router/dev": "^7.2.0",
100
100
  "@types/react": "^18.3.10 || ^19.0.0",
101
101
  "miniflare": "^3.20241205.0",
@@ -104,6 +104,9 @@
104
104
  "wrangler": "^4.2.0"
105
105
  },
106
106
  "peerDependenciesMeta": {
107
+ "@hono/node-server": {
108
+ "optional": false
109
+ },
107
110
  "@cloudflare/workers-types": {
108
111
  "optional": true
109
112
  },