react-router-hono-server 2.10.0 → 2.12.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
@@ -123,6 +123,10 @@ export default defineConfig({
123
123
  > [!TIP]
124
124
  > Check this [example](./examples/bun/simple/) to see how to use it.
125
125
 
126
+ > [!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
+ > Check this [example](./examples/bun/simple-bun-runtime/) to see how to use it.
129
+
126
130
  ```ts
127
131
  // vite.config.ts
128
132
  import { reactRouter } from "@react-router/dev/vite";
@@ -139,6 +143,53 @@ export default defineConfig({
139
143
  });
140
144
  ```
141
145
 
146
+ ##### Using `bun --bun` flag?
147
+ > [!TIP]
148
+ > Check this [example](./examples/bun/simple-bun-runtime/) to see how to use it.
149
+
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
+
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.
153
+
154
+
155
+ ```ts
156
+ import { isbot } from "isbot";
157
+ import { renderToReadableStream } from "react-dom/server.bun";
158
+ import type { AppLoadContext, EntryContext } from "react-router";
159
+ import { ServerRouter } from "react-router";
160
+
161
+ export default async function handleRequest(
162
+ request: Request,
163
+ responseStatusCode: number,
164
+ responseHeaders: Headers,
165
+ routerContext: EntryContext,
166
+ _loadContext: AppLoadContext
167
+ ) {
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
+ }
184
+
185
+ responseHeaders.set("Content-Type", "text/html");
186
+ return new Response(body, {
187
+ headers: responseHeaders,
188
+ status: responseStatusCode,
189
+ });
190
+ }
191
+ ```
192
+
142
193
  #### Cloudflare Workers
143
194
  > [!TIP]
144
195
  > Check this [example](./examples/cloudflare/simple/) to see how to use it.
@@ -165,6 +216,18 @@ export default defineConfig({
165
216
  });
166
217
  ```
167
218
 
219
+ ##### React 19
220
+ > [!IMPORTANT]
221
+ > Check this [example](./examples/cloudflare/simple-19/) to see how to use it.
222
+
223
+ > [!TIP]
224
+ > You may need to add the `force_react_19` flag to the `reactRouterHonoServer` plugin config.
225
+
226
+ ```ts
227
+ // vite.config.ts
228
+ reactRouterHonoServer({ runtime: "cloudflare", flag: { force_react_19: true } }), // add this
229
+ ```
230
+
168
231
  #### AWS Lambda
169
232
  > [!TIP]
170
233
  > AWS shares the same runtime as Node.
@@ -513,7 +576,7 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
513
576
  * The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance.
514
577
  *
515
578
  * If you want this behavior, set it to `true`
516
- *
579
+ *
517
580
  * 🚨 Setting this to `true` can break `request.clone()` if you later check `instanceof Request`.
518
581
  *
519
582
  * {@link https://github.com/honojs/node-server?tab=readme-ov-file#overrideglobalobjects}
@@ -521,6 +584,25 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
521
584
  * @default false
522
585
  */
523
586
  overrideGlobalObjects?: boolean;
587
+ /**
588
+ * Customize the hostname of the node server
589
+ */
590
+ hostname?: string;
591
+ /**
592
+ * Customize the serve static options
593
+ */
594
+ serveStaticOptions?: {
595
+ /**
596
+ * Customize the public assets (what's in your `public` directory) serve static options.
597
+ *
598
+ */
599
+ publicAssets?: Omit<ServeStaticOptions<E>, "root">;
600
+ /**
601
+ * Customize the client assets (what's in your `build/client/assets` directory - React Router) serve static options.
602
+ *
603
+ */
604
+ clientAssets?: Omit<ServeStaticOptions<E>, "root">;
605
+ };
524
606
  }
525
607
  ```
526
608
 
@@ -533,6 +615,21 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
533
615
  * {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
534
616
  */
535
617
  customBunServer?: Serve & ServeOptions;
618
+ /**
619
+ * Customize the serve static options
620
+ */
621
+ serveStaticOptions?: {
622
+ /**
623
+ * Customize the public assets (what's in your `public` directory) serve static options.
624
+ *
625
+ */
626
+ publicAssets?: Omit<ServeStaticOptions<E>, "root">;
627
+ /**
628
+ * Customize the client assets (what's in your `build/client/assets` directory - React Router) serve static options.
629
+ *
630
+ */
631
+ clientAssets?: Omit<ServeStaticOptions<E>, "root">;
632
+ };
536
633
  }
537
634
  ```
538
635
 
@@ -564,7 +661,7 @@ interface HonoAWSServerOptions<E extends Env = BlankEnv> extends Omit<HonoServer
564
661
  > 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`.
565
662
  >
566
663
  > `redirect` will use `c.redirect` for "normal" requests and a single-fetch-like response for React Router `.data` requests.
567
- >
664
+ >
568
665
  > 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.
569
666
  >
570
667
  > 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.
@@ -659,7 +756,7 @@ export default await createHonoServer({
659
756
  });
660
757
  ```
661
758
 
662
- ### Creating custom Middleware
759
+ ### Creating custom Hono Middleware
663
760
 
664
761
  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`.
665
762
 
@@ -681,6 +778,18 @@ export default await createHonoServer({
681
778
  });
682
779
  ```
683
780
 
781
+ ### Using React Router Middleware (unstable future)
782
+ You can use React Router middleware with this package.
783
+
784
+ > [!TIP]
785
+ > Check this [example](./examples/node/simple-future-middleware/) to see how to use it.
786
+
787
+ > [!IMPORTANT]
788
+ > Please note that this is an unstable feature and could change in the future.
789
+ >
790
+ > If you already have a custom `getLoadContext` function, you now have to return a `Map` from it. Check the example for more information.
791
+
792
+
684
793
  ### Using WebSockets
685
794
  #### Node
686
795
  This package has a built-in helper to use `@hono/node-ws`
@@ -855,7 +964,6 @@ Add the pre-render option to your `react-router.config.ts`
855
964
  import type { Config } from "@react-router/dev/config";
856
965
 
857
966
  export default {
858
- serverBuildFile: "assets/server-build.js", // 🚨 Dont forget this
859
967
  prerender: ["/"],
860
968
  } satisfies Config;
861
969
  ```
@@ -2,10 +2,10 @@ import * as hono_aws_lambda from 'hono/aws-lambda';
2
2
  import * as hono_types from 'hono/types';
3
3
  import { BlankEnv } from 'hono/types';
4
4
  import { Env, Hono } from 'hono';
5
- import { H as HonoServerOptionsBase, W as WithoutWebsocket } from '../helpers-DZ1r-Y-D.js';
6
- export { c as createGetLoadContext } from '../helpers-DZ1r-Y-D.js';
7
- import 'react-router';
5
+ import { H as HonoServerOptionsBase, W as WithoutWebsocket } from '../helpers-BKrW-3-B.js';
6
+ export { c as createGetLoadContext } from '../helpers-BKrW-3-B.js';
8
7
  import 'hono/ws';
8
+ import 'react-router';
9
9
 
10
10
  interface CognitoIdentity {
11
11
  cognitoIdentityId: string;
@@ -67,6 +67,14 @@ type HonoServerOptions<E extends Env = BlankEnv> = HonoAWSServerOptions<E> & Omi
67
67
  *
68
68
  * @param config {@link HonoServerOptions} - The configuration options for the server
69
69
  */
70
- declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptions<E>): Promise<Hono<E, hono_types.BlankSchema, "/"> | Handler | ((event: hono_aws_lambda.LambdaEvent, lambdaContext?: hono_aws_lambda.LambdaContext) => Promise<hono_aws_lambda.APIGatewayProxyResult>)>;
70
+ declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptions<E>): Promise<Hono<E, hono_types.BlankSchema, "/"> | Handler | (<L extends hono_aws_lambda.LambdaEvent>(event: L, lambdaContext?: hono_aws_lambda.LambdaContext) => Promise<hono_aws_lambda.APIGatewayProxyResult & (L extends {
71
+ multiValueHeaders: Record<string, string[]>;
72
+ } ? {
73
+ headers?: undefined;
74
+ multiValueHeaders: Record<string, string[]>;
75
+ } : {
76
+ headers: Record<string, string>;
77
+ multiValueHeaders?: undefined;
78
+ })>)>;
71
79
 
72
80
  export { type HonoServerOptions, createHonoServer };
@@ -1,8 +1,9 @@
1
1
  import {
2
2
  bindIncomingRequestSocketInfo,
3
3
  createGetLoadContext,
4
+ getBuildMode,
4
5
  importBuild
5
- } from "../chunk-J24YMSRS.js";
6
+ } from "../chunk-IZYOBD55.js";
6
7
  import {
7
8
  cache
8
9
  } from "../chunk-V3H4JZ4H.js";
@@ -21,7 +22,7 @@ async function createHonoServer(options) {
21
22
  invokeMode: options?.invokeMode ?? "default",
22
23
  defaultLogger: options?.defaultLogger ?? true
23
24
  };
24
- const mode = import.meta.env.MODE || "production";
25
+ const mode = getBuildMode();
25
26
  const PRODUCTION = mode === "production";
26
27
  const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
27
28
  const app = new Hono(mergedOptions.app);
@@ -1,10 +1,11 @@
1
1
  import { Serve, ServeOptions } from 'bun';
2
2
  import { Env } from 'hono';
3
+ import { ServeStaticOptions } from 'hono/serve-static';
3
4
  import { BlankEnv } from 'hono/types';
4
- import { H as HonoServerOptionsBase, a as WithWebsocket, W as WithoutWebsocket } from '../helpers-DZ1r-Y-D.js';
5
- export { c as createGetLoadContext } from '../helpers-DZ1r-Y-D.js';
6
- import 'react-router';
5
+ import { H as HonoServerOptionsBase, a as WithWebsocket, W as WithoutWebsocket } from '../helpers-BKrW-3-B.js';
6
+ export { c as createGetLoadContext } from '../helpers-BKrW-3-B.js';
7
7
  import 'hono/ws';
8
+ import 'react-router';
8
9
 
9
10
  type CustomBunServer = Serve & ServeOptions & {
10
11
  websocket?: unknown;
@@ -16,6 +17,21 @@ interface HonoBunServerOptions<E extends Env = BlankEnv> extends HonoServerOptio
16
17
  * {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
17
18
  */
18
19
  customBunServer?: Partial<CustomBunServer>;
20
+ /**
21
+ * Customize the serve static options
22
+ */
23
+ serveStaticOptions?: {
24
+ /**
25
+ * Customize the public assets (what's in your `public` directory) serve static options.
26
+ *
27
+ */
28
+ publicAssets?: Omit<ServeStaticOptions<E>, "root">;
29
+ /**
30
+ * Customize the client assets (what's in your `build/client/assets` directory - React Router) serve static options.
31
+ *
32
+ */
33
+ clientAssets?: Omit<ServeStaticOptions<E>, "root">;
34
+ };
19
35
  }
20
36
  type HonoServerOptionsWithWebSocket<E extends Env = BlankEnv> = HonoBunServerOptions<E> & WithWebsocket<E>;
21
37
  type HonoServerOptionsWithoutWebSocket<E extends Env = BlankEnv> = HonoBunServerOptions<E> & WithoutWebsocket<E>;
@@ -3,9 +3,10 @@ import {
3
3
  cleanUpgradeListeners,
4
4
  createGetLoadContext,
5
5
  createWebSocket,
6
+ getBuildMode,
6
7
  importBuild,
7
8
  patchUpgradeListener
8
- } from "../chunk-J24YMSRS.js";
9
+ } from "../chunk-IZYOBD55.js";
9
10
  import {
10
11
  cache
11
12
  } from "../chunk-V3H4JZ4H.js";
@@ -23,7 +24,7 @@ async function createHonoServer(options) {
23
24
  port: options?.port || Number(options?.customBunServer?.port) || Number(process.env.PORT) || 3e3,
24
25
  defaultLogger: options?.defaultLogger ?? true
25
26
  };
26
- const mode = import.meta.env.MODE || "production";
27
+ const mode = getBuildMode();
27
28
  const PRODUCTION = mode === "production";
28
29
  const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
29
30
  const app = new Hono(mergedOptions.app);
@@ -39,13 +40,19 @@ async function createHonoServer(options) {
39
40
  `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
40
41
  cache(60 * 60 * 24 * 365),
41
42
  // 1 year
42
- serveStatic({ root: clientBuildPath })
43
+ serveStatic({
44
+ root: clientBuildPath,
45
+ ...mergedOptions.serveStaticOptions?.clientAssets
46
+ })
43
47
  );
44
48
  app.use(
45
49
  "*",
46
50
  cache(60 * 60),
47
51
  // 1 hour
48
- serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" })
52
+ serveStatic({
53
+ root: PRODUCTION ? clientBuildPath : "./public",
54
+ ...mergedOptions.serveStaticOptions?.publicAssets
55
+ })
49
56
  );
50
57
  if (mergedOptions.defaultLogger) {
51
58
  app.use("*", logger());
@@ -1,10 +1,10 @@
1
1
  import * as hono_types from 'hono/types';
2
2
  import { BlankEnv } from 'hono/types';
3
3
  import { Env, Hono } from 'hono';
4
- import { H as HonoServerOptionsBase, W as WithoutWebsocket } from '../helpers-DZ1r-Y-D.js';
5
- export { c as createGetLoadContext } from '../helpers-DZ1r-Y-D.js';
6
- import 'react-router';
4
+ import { H as HonoServerOptionsBase, W as WithoutWebsocket } from '../helpers-BKrW-3-B.js';
5
+ export { c as createGetLoadContext } from '../helpers-BKrW-3-B.js';
7
6
  import 'hono/ws';
7
+ import 'react-router';
8
8
 
9
9
  interface HonoCloudflareOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {
10
10
  }
@@ -1,8 +1,9 @@
1
1
  import {
2
2
  bindIncomingRequestSocketInfo,
3
3
  createGetLoadContext,
4
+ getBuildMode,
4
5
  importBuild
5
- } from "../chunk-J24YMSRS.js";
6
+ } from "../chunk-IZYOBD55.js";
6
7
  import {
7
8
  cache
8
9
  } from "../chunk-V3H4JZ4H.js";
@@ -18,7 +19,7 @@ async function createHonoServer(options) {
18
19
  ...options,
19
20
  defaultLogger: options?.defaultLogger ?? true
20
21
  };
21
- const mode = import.meta.env.MODE || "production";
22
+ const mode = getBuildMode();
22
23
  const PRODUCTION = mode === "production";
23
24
  const app = new Hono(mergedOptions.app);
24
25
  await mergedOptions.beforeAll?.(app);
@@ -1,14 +1,15 @@
1
1
  import { AddressInfo } from 'node:net';
2
2
  import { ServerType } from '@hono/node-server';
3
+ import { ServeStaticOptions } from '@hono/node-server/serve-static';
3
4
  import { Env, Hono } from 'hono';
4
5
  import { BlankEnv } from 'hono/types';
5
- import { H as HonoServerOptionsBase, a as WithWebsocket, W as WithoutWebsocket } from '../helpers-DZ1r-Y-D.js';
6
- export { c as createGetLoadContext } from '../helpers-DZ1r-Y-D.js';
6
+ import { H as HonoServerOptionsBase, a as WithWebsocket, W as WithoutWebsocket } from '../helpers-BKrW-3-B.js';
7
+ export { c as createGetLoadContext } from '../helpers-BKrW-3-B.js';
7
8
  import { ServerOptions, createServer } from 'node:http';
8
9
  import { ServerOptions as ServerOptions$2, createServer as createServer$2, SecureServerOptions, createSecureServer } from 'node:http2';
9
10
  import { ServerOptions as ServerOptions$1, createServer as createServer$1 } from 'node:https';
10
- import 'react-router';
11
11
  import 'hono/ws';
12
+ import 'react-router';
12
13
 
13
14
  type createHttpOptions = {
14
15
  serverOptions?: ServerOptions;
@@ -63,6 +64,25 @@ interface HonoNodeServerOptions<E extends Env = BlankEnv> extends HonoServerOpti
63
64
  * @default false
64
65
  */
65
66
  overrideGlobalObjects?: boolean;
67
+ /**
68
+ * Customize the hostname of the node server
69
+ */
70
+ hostname?: string;
71
+ /**
72
+ * Customize the serve static options
73
+ */
74
+ serveStaticOptions?: {
75
+ /**
76
+ * Customize the public assets (what's in your `public` directory) serve static options.
77
+ *
78
+ */
79
+ publicAssets?: Omit<ServeStaticOptions<E>, "root">;
80
+ /**
81
+ * Customize the client assets (what's in your `build/client/assets` directory - React Router) serve static options.
82
+ *
83
+ */
84
+ clientAssets?: Omit<ServeStaticOptions<E>, "root">;
85
+ };
66
86
  }
67
87
  type HonoServerOptionsWithWebSocket<E extends Env = BlankEnv> = HonoNodeServerOptions<E> & WithWebsocket<E>;
68
88
  type HonoServerOptionsWithoutWebSocket<E extends Env = BlankEnv> = HonoNodeServerOptions<E> & WithoutWebsocket<E>;
@@ -3,9 +3,10 @@ import {
3
3
  cleanUpgradeListeners,
4
4
  createGetLoadContext,
5
5
  createWebSocket,
6
+ getBuildMode,
6
7
  importBuild,
7
8
  patchUpgradeListener
8
- } from "../chunk-J24YMSRS.js";
9
+ } from "../chunk-IZYOBD55.js";
9
10
  import {
10
11
  cache
11
12
  } from "../chunk-V3H4JZ4H.js";
@@ -32,7 +33,7 @@ async function createHonoServer(options) {
32
33
  defaultLogger: options?.defaultLogger ?? true,
33
34
  overrideGlobalObjects: options?.overrideGlobalObjects ?? false
34
35
  };
35
- const mode = import.meta.env.MODE || "production";
36
+ const mode = getBuildMode();
36
37
  const PRODUCTION = mode === "production";
37
38
  const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
38
39
  const app = new Hono(mergedOptions.app);
@@ -48,13 +49,13 @@ async function createHonoServer(options) {
48
49
  `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
49
50
  cache(60 * 60 * 24 * 365),
50
51
  // 1 year
51
- serveStatic({ root: clientBuildPath })
52
+ serveStatic({ root: clientBuildPath, ...mergedOptions.serveStaticOptions?.clientAssets })
52
53
  );
53
54
  app.use(
54
55
  "*",
55
56
  cache(60 * 60),
56
57
  // 1 hour
57
- serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" })
58
+ serveStatic({ root: PRODUCTION ? clientBuildPath : "./public", ...mergedOptions.serveStaticOptions?.publicAssets })
58
59
  );
59
60
  if (mergedOptions.defaultLogger) {
60
61
  app.use("*", logger());
@@ -85,7 +86,8 @@ async function createHonoServer(options) {
85
86
  ...app,
86
87
  ...mergedOptions.customNodeServer,
87
88
  port: mergedOptions.port,
88
- overrideGlobalObjects: mergedOptions.overrideGlobalObjects
89
+ overrideGlobalObjects: mergedOptions.overrideGlobalObjects,
90
+ hostname: mergedOptions.hostname
89
91
  },
90
92
  mergedOptions.listeningListener
91
93
  );
@@ -9,7 +9,7 @@ async function createWebSocket({ app, enabled }) {
9
9
  if (!enabled) {
10
10
  return defaultWebSocket;
11
11
  }
12
- const mode = import.meta.env.MODE;
12
+ const mode = process.env.NODE_ENV === "development" ? "development" : "production";
13
13
  const DEV = mode === "development";
14
14
  const runtime = import.meta.env.REACT_ROUTER_HONO_SERVER_RUNTIME;
15
15
  if (DEV || runtime === "node") {
@@ -65,7 +65,7 @@ function patchUpgradeListener(httpServer) {
65
65
  }
66
66
  }
67
67
  function bindIncomingRequestSocketInfo() {
68
- return createMiddleware(async (c, next) => {
68
+ return createMiddleware((c, next) => {
69
69
  c.env.server = {
70
70
  incoming: {
71
71
  socket: {
@@ -79,7 +79,7 @@ function bindIncomingRequestSocketInfo() {
79
79
  });
80
80
  }
81
81
  async function importBuild() {
82
- return import(
82
+ return await import(
83
83
  // @ts-expect-error - Virtual module provided by React Router at build time
84
84
  "virtual:react-router/server-build"
85
85
  );
@@ -87,10 +87,8 @@ async function importBuild() {
87
87
  function createGetLoadContext(getLoadContext) {
88
88
  return getLoadContext;
89
89
  }
90
- async function getReactVersion() {
91
- const reactPackage = await import("react");
92
- const version = reactPackage.default.version || reactPackage.version;
93
- return Number.parseInt(version.split(".")[0]);
90
+ function getBuildMode() {
91
+ return process.env.NODE_ENV === "development" ? "development" : "production";
94
92
  }
95
93
 
96
94
  export {
@@ -100,5 +98,5 @@ export {
100
98
  bindIncomingRequestSocketInfo,
101
99
  importBuild,
102
100
  createGetLoadContext,
103
- getReactVersion
101
+ getBuildMode
104
102
  };
package/dist/cli.js CHANGED
@@ -19,7 +19,7 @@ import { createHonoServer } from "react-router-hono-server/${runtime}";
19
19
  export default await createHonoServer();`;
20
20
  var file = command({
21
21
  name: "file",
22
- async handler() {
22
+ handler() {
23
23
  const serverFilePath = path.resolve(process.cwd(), "app", "server.ts");
24
24
  fs.writeFileSync(serverFilePath, serverFile);
25
25
  console.log(`\x1B[33m\u2728 File created at ${serverFilePath}\x1B[0m`);
@@ -27,7 +27,7 @@ var file = command({
27
27
  });
28
28
  var folder = command({
29
29
  name: "folder",
30
- async handler() {
30
+ handler() {
31
31
  const serverFilePath = path.resolve(process.cwd(), "app", "server", "index.ts");
32
32
  if (!fs.existsSync(serverFilePath)) {
33
33
  fs.mkdirSync(path.dirname(serverFilePath), { recursive: true });
package/dist/dev.d.ts CHANGED
@@ -3,13 +3,7 @@ import { Plugin } from 'vite';
3
3
 
4
4
  type Runtime = "node" | "bun" | "cloudflare" | "aws";
5
5
 
6
- type ReactRouterHonoServerPluginOptions = {
7
- /**
8
- * The runtime to use for the server.
9
- *
10
- * Defaults to `node`.
11
- */
12
- runtime?: Runtime;
6
+ type ReactRouterHonoServerPluginOptionsBase = {
13
7
  /**
14
8
  * The path to the server file, relative to `vite.config.ts`.
15
9
  *
@@ -40,6 +34,26 @@ type ReactRouterHonoServerPluginOptions = {
40
34
  export?: DevServerOptions["export"];
41
35
  };
42
36
  };
37
+ type ReactRouterHonoServerPluginOptionsDefault = ReactRouterHonoServerPluginOptionsBase & {
38
+ /**
39
+ * The runtime to use for the server.
40
+ *
41
+ * Defaults to `node`.
42
+ */
43
+ runtime?: Runtime;
44
+ };
45
+ type ReactRouterHonoServerPluginOptionsCloudflare = ReactRouterHonoServerPluginOptionsBase & {
46
+ /**
47
+ * The runtime to use for the server.
48
+ *
49
+ * Defaults to `node`.
50
+ */
51
+ runtime: Extract<Runtime, "cloudflare">;
52
+ flag?: {
53
+ force_react_19?: boolean;
54
+ };
55
+ };
56
+ type ReactRouterHonoServerPluginOptions = ReactRouterHonoServerPluginOptionsDefault | ReactRouterHonoServerPluginOptionsCloudflare;
43
57
  declare function reactRouterHonoServer(options?: ReactRouterHonoServerPluginOptions): Plugin;
44
58
 
45
59
  export { reactRouterHonoServer };
package/dist/dev.js CHANGED
@@ -1,15 +1,12 @@
1
- import {
2
- getReactVersion
3
- } from "./chunk-J24YMSRS.js";
4
-
5
1
  // src/dev.ts
6
2
  import fs from "node:fs";
7
3
  import path from "node:path";
8
4
  import honoDevServer from "@hono/vite-dev-server";
9
5
  import bunAdapter from "@hono/vite-dev-server/bun";
10
6
  import nodeAdapter from "@hono/vite-dev-server/node";
11
- var virtualModuleId = "\0virtual:react-router-hono-server/server";
12
- var reactRouterExport = "export {serverManifest as assets, assetsBuildDirectory, basename, entry, future, isSpaMode, publicPath, routes };";
7
+ var REACT_ROUTER_VIRTUAL_MODULE_ID = "\0virtual:react-router/server-build";
8
+ var VIRTUAL_MODULE_ID = "\0virtual:react-router-hono-server/server";
9
+ var REACT_ROUTER_EXPORT = "export { serverManifest as assets, assetsBuildDirectory, basename, entry, future, isSpaMode, prerender, publicPath, routes, ssr };";
13
10
  function reactRouterHonoServer(options = {}) {
14
11
  const runtime = options.runtime || "node";
15
12
  let pluginConfig;
@@ -18,12 +15,12 @@ function reactRouterHonoServer(options = {}) {
18
15
  name: "react-router-hono-server",
19
16
  enforce: "post",
20
17
  resolveId(id) {
21
- if (id === virtualModuleId) {
18
+ if (id === VIRTUAL_MODULE_ID) {
22
19
  return id;
23
20
  }
24
21
  },
25
22
  load(id) {
26
- if (id === virtualModuleId) {
23
+ if (id === VIRTUAL_MODULE_ID) {
27
24
  return `
28
25
  // generated by react-router-hono-server/dev
29
26
  import { createHonoServer } from "react-router-hono-server/${runtime}";
@@ -32,7 +29,7 @@ function reactRouterHonoServer(options = {}) {
32
29
  `;
33
30
  }
34
31
  },
35
- async config(config) {
32
+ async config(config, env) {
36
33
  pluginConfig = resolvePluginConfig(config, options);
37
34
  if (!pluginConfig) {
38
35
  return;
@@ -42,7 +39,7 @@ function reactRouterHonoServer(options = {}) {
42
39
  "\x1B[33mThe unstable_viteEnvironmentApi is enabled.\nThis is experimental and may break your build.\x1B[0m\n"
43
40
  );
44
41
  }
45
- if (runtime === "cloudflare" && !config.plugins?.find((p) => p && "name" in p && p.name === "react-router-cloudflare-vite-dev-proxy")) {
42
+ if (env.mode === "development" && runtime === "cloudflare" && !config.plugins?.find((p) => p && "name" in p && p.name === "react-router-cloudflare-vite-dev-proxy")) {
46
43
  console.warn(
47
44
  `\x1B[31mMissing cloudflareDevProxy() in your vite.config.ts.
48
45
  Please add it to your plugins: import { cloudflareDevProxy } from "@react-router/dev/vite/cloudflare";\x1B[0m
@@ -73,7 +70,7 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
73
70
  }
74
71
  let alias = void 0;
75
72
  if (runtime === "cloudflare") {
76
- const reactVersion = await getReactVersion();
73
+ const reactVersion = await getReactVersion(pluginConfig);
77
74
  alias = {
78
75
  "react-dom/server": reactVersion >= 19 ? "react-dom/server.edge" : "react-dom/server.browser"
79
76
  };
@@ -89,14 +86,20 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
89
86
  rollupOptions: {
90
87
  input: pluginConfig.serverEntryPoint,
91
88
  output: {
92
- entryFileNames: "index.js",
89
+ entryFileNames: (chunk) => {
90
+ chunk.facadeModuleId = REACT_ROUTER_VIRTUAL_MODULE_ID;
91
+ return "index.js";
92
+ },
93
+ // not invoked when target is webworker (single file output)
93
94
  chunkFileNames: (chunk) => {
94
95
  if (chunk.name === "server-build") {
95
96
  return reactRouterBuildFile;
96
97
  }
97
98
  return "assets/[name]-[hash].js";
98
99
  },
99
- footer: runtime === "cloudflare" ? reactRouterExport : void 0
100
+ // We are doing that because in this case, we build a single file that only exports the Hono server
101
+ // RR needs its exports for prerendering
102
+ footer: runtime === "cloudflare" ? REACT_ROUTER_EXPORT : void 0
100
103
  }
101
104
  }
102
105
  }
@@ -120,12 +123,25 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
120
123
  }
121
124
  console.log("Cleaning up server exports...");
122
125
  const buildPath = path.join(pluginConfig.rootDirectory, pluginConfig.buildDirectory, "server", "index.js");
123
- let content = await fs.promises.readFile(buildPath, "utf-8");
124
- content = content.replace(reactRouterExport, "");
125
- if (await getReactVersion() >= 19) {
126
- content = content.replace(/react-dom\/server\.browser/g, "react-dom/server.edge");
126
+ let serverFile = await fs.promises.readFile(buildPath, "utf-8").catch((e) => {
127
+ if (e.code === "ENOENT") {
128
+ console.error("\x1B[31m\nThe server was not built\x1B[0m");
129
+ if (pluginConfig?.flag?.force_react_19) {
130
+ console.error(
131
+ "\x1B[31m\nYou are forcing React 19 but the server failed to be built by React Router.\nCheck your dependencies, but it's possible that your project is still using React 18 from a node_modules root (monorepo?)\n\x1B[0m"
132
+ );
133
+ }
134
+ }
135
+ return null;
136
+ });
137
+ if (!serverFile) {
138
+ return;
139
+ }
140
+ serverFile = serverFile.replace(REACT_ROUTER_EXPORT, "");
141
+ if (await getReactVersion(pluginConfig) >= 19) {
142
+ serverFile = serverFile.replace(/react-dom\/server\.browser/g, "react-dom/server.edge");
127
143
  }
128
- await fs.promises.writeFile(buildPath, content);
144
+ await fs.promises.writeFile(buildPath, serverFile);
129
145
  console.log("\x1B[32mAll done!\x1B[0m");
130
146
  },
131
147
  async configureServer(server) {
@@ -151,12 +167,12 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
151
167
  export: options.dev?.export || "default",
152
168
  exclude: [
153
169
  new RegExp(
154
- `^(?=\\/${pluginConfig.appDirectory.replace(/^\/+|\/+$/g, "").replaceAll("/", "\\/")}\\/)((?!.*\\.data(\\?|$)).*\\..*(\\?.*)?$)`
170
+ `^(?=\\/${pluginConfig.appDirectory.replace(/^[/\\]+|[/\\]+$/g, "").replaceAll(/[/\\]+/g, "/")}\\/)((?!.*\\.data(\\?|$)).*\\..*(\\?.*)?$)`
155
171
  ),
156
172
  /\?import(\?.*)?$/,
157
173
  /^\/@.+$/,
158
174
  /^\/node_modules\/.*/,
159
- `/${pluginConfig.appDirectory}/**/.*/**`,
175
+ `^(?=\\/${pluginConfig.appDirectory.replace(/^[/\\]+|[/\\]+$/g, "").replace(/[/\\]+/g, "/")}/**/.*/**)`,
160
176
  ...pluginConfig.dev?.exclude || []
161
177
  ]
162
178
  });
@@ -198,7 +214,8 @@ function resolvePluginConfig(config, options) {
198
214
  dev: options.dev,
199
215
  serverBuildFile,
200
216
  basename,
201
- future
217
+ future,
218
+ flag: isCloudflareOptions(options) ? options.flag : {}
202
219
  };
203
220
  }
204
221
  var warned = false;
@@ -214,7 +231,7 @@ function findDefaultServerEntry(appDirectory) {
214
231
  if (!warned) {
215
232
  console.warn(
216
233
  `\x1B[33mNo server entry point found.
217
- Will use a virtual module (${virtualModuleId}) with a default Hono server.
234
+ Will use a virtual module (${VIRTUAL_MODULE_ID}) with a default Hono server.
218
235
 
219
236
  To customize the server, create one of the following files:
220
237
  - ${fileWay} (npx react-router-hono-server reveal file)
@@ -224,7 +241,18 @@ You can also set the \`serverEntryPoint\` option in the reactRouterHonoServer pl
224
241
  );
225
242
  warned = true;
226
243
  }
227
- return virtualModuleId;
244
+ return VIRTUAL_MODULE_ID;
245
+ }
246
+ async function getReactVersion(pluginConfig) {
247
+ if (pluginConfig?.flag?.force_react_19) {
248
+ return 19;
249
+ }
250
+ const reactPackage = await import("react");
251
+ const version = reactPackage.default.version || reactPackage.version;
252
+ return Number.parseInt(version.split(".")[0]);
253
+ }
254
+ function isCloudflareOptions(options) {
255
+ return options.runtime === "cloudflare";
228
256
  }
229
257
  export {
230
258
  reactRouterHonoServer
@@ -1,8 +1,11 @@
1
- import * as react_router from 'react-router';
2
- import { ServerBuild, AppLoadContext } from 'react-router';
3
1
  import * as hono from 'hono';
4
2
  import { Env, Hono, Context } from 'hono';
5
3
  import { UpgradeWebSocket } from 'hono/ws';
4
+ import { ServerBuild, UNSAFE_MiddlewareEnabled, unstable_RouterContext, AppLoadContext } from 'react-router';
5
+
6
+ type ReactRouterHonoServerAppLoadContext = UNSAFE_MiddlewareEnabled extends true
7
+ ? Map<unstable_RouterContext, unknown>
8
+ : AppLoadContext;
6
9
 
7
10
  interface HonoServerOptionsBase<E extends Env> {
8
11
  /**
@@ -46,7 +49,7 @@ interface HonoServerOptionsBase<E extends Env> {
46
49
  build: ServerBuild;
47
50
  mode: string;
48
51
  }
49
- ) => Promise<AppLoadContext> | AppLoadContext;
52
+ ) => Promise<ReactRouterHonoServerAppLoadContext> | ReactRouterHonoServerAppLoadContext;
50
53
  /**
51
54
  * Hook to add middleware that runs before any built-in middleware, including assets serving.
52
55
  *
@@ -95,6 +98,6 @@ interface WithoutWebsocket<E extends Env> {
95
98
  declare function createGetLoadContext(getLoadContext: HonoServerOptionsBase<Env>["getLoadContext"]): ((c: hono.Context<Env, any, {}>, options: {
96
99
  build: ServerBuild;
97
100
  mode: string;
98
- }) => Promise<react_router.AppLoadContext> | react_router.AppLoadContext) | undefined;
101
+ }) => Promise<ReactRouterHonoServerAppLoadContext> | ReactRouterHonoServerAppLoadContext) | undefined;
99
102
 
100
103
  export { type HonoServerOptionsBase as H, type WithoutWebsocket as W, type WithWebsocket as a, createGetLoadContext as c };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-router-hono-server",
3
- "version": "2.10.0",
3
+ "version": "2.12.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
  "exports": {
@@ -54,17 +54,6 @@
54
54
  }
55
55
  }
56
56
  },
57
- "scripts": {
58
- "test": "vitest run",
59
- "test:cov": "vitest run --coverage",
60
- "build": "tsup",
61
- "build:watch": "npm run build -- --watch",
62
- "prepublishOnly": "npm run build",
63
- "check": "biome check .",
64
- "check:fix": "biome check --fix .",
65
- "typecheck": "tsc",
66
- "validate": "npm run check && npm run tsc"
67
- },
68
57
  "author": "",
69
58
  "license": "ISC",
70
59
  "repository": {
@@ -77,35 +66,37 @@
77
66
  "bin": {
78
67
  "react-router-hono-server": "dist/cli.js"
79
68
  },
80
- "files": ["dist"],
69
+ "files": [
70
+ "dist"
71
+ ],
81
72
  "homepage": "https://github.com/rphlmr/react-router-hono-server#readme",
82
73
  "dependencies": {
83
74
  "@drizzle-team/brocli": "^0.11.0",
84
- "@hono/node-server": "^1.13.7",
85
- "@hono/node-ws": "^1.0.4",
86
- "@hono/vite-dev-server": "^0.17.0",
87
- "hono": "^4.6.11"
75
+ "@hono/node-server": "^1.14.0",
76
+ "@hono/node-ws": "^1.1.1",
77
+ "@hono/vite-dev-server": "^0.19.0",
78
+ "hono": "^4.7.5"
88
79
  },
89
80
  "devDependencies": {
90
81
  "@biomejs/biome": "^1.9.4",
91
- "@cloudflare/workers-types": "^4.20241112.0",
92
- "@types/bun": "^1.1.14",
93
- "@types/node": "^22.9.3",
94
- "@vitest/coverage-v8": "^2.1.5",
95
- "lefthook": "^1.8.4",
82
+ "@cloudflare/workers-types": "^4.20250405.0",
83
+ "@types/bun": "^1.2.8",
84
+ "@types/node": "^22.14.0",
85
+ "@vitest/coverage-v8": "^3.1.1",
86
+ "lefthook": "^1.11.6",
96
87
  "npm-run-all": "^4.1.5",
97
- "tsup": "^8.3.5",
98
- "typescript": "^5.7.2",
99
- "vitest": "^2.1.5"
88
+ "tsup": "^8.4.0",
89
+ "typescript": "^5.8.3",
90
+ "vitest": "^3.1.1"
100
91
  },
101
92
  "peerDependencies": {
102
- "@cloudflare/workers-types": "^4.20241112.0",
93
+ "@cloudflare/workers-types": "^4.20250317.0",
103
94
  "@types/react": "^18.3.10 || ^19.0.0",
104
95
  "@react-router/dev": "^7.2.0",
105
96
  "miniflare": "^3.20241205.0",
106
97
  "react-router": "^7.2.0",
107
- "vite": "^5.1.0 || ^6.0.0",
108
- "wrangler": "^3.91.0"
98
+ "vite": "^6.0.0",
99
+ "wrangler": "^4.2.0"
109
100
  },
110
101
  "peerDependenciesMeta": {
111
102
  "@cloudflare/workers-types": {
@@ -120,5 +111,16 @@
120
111
  },
121
112
  "engines": {
122
113
  "node": ">=22.12.0"
114
+ },
115
+ "scripts": {
116
+ "test": "vitest run",
117
+ "test:cov": "vitest run --coverage",
118
+ "build": "tsup",
119
+ "build:watch": "npm run build -- --watch",
120
+ "check": "biome check .",
121
+ "check:fix": "biome check --fix .",
122
+ "typecheck": "tsc",
123
+ "validate": "npm run check && npm run tsc",
124
+ "clear-all": "rm -rf node_modules pnpm-lock.yaml && find ./examples -type d -name 'node_modules' -exec rm -rf {} + && find ./examples -name 'pnpm-lock.yaml' -exec rm -f {} +"
123
125
  }
124
- }
126
+ }