react-router-hono-server 2.9.0 → 2.11.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.
@@ -659,7 +722,7 @@ export default await createHonoServer({
659
722
  });
660
723
  ```
661
724
 
662
- ### Creating custom Middleware
725
+ ### Creating custom Hono Middleware
663
726
 
664
727
  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
728
 
@@ -681,6 +744,18 @@ export default await createHonoServer({
681
744
  });
682
745
  ```
683
746
 
747
+ ### Using React Router Middleware (unstable future)
748
+ You can use React Router middleware with this package.
749
+
750
+ > [!TIP]
751
+ > Check this [example](./examples/node/simple-future-middleware/) to see how to use it.
752
+
753
+ > [!IMPORTANT]
754
+ > Please note that this is an unstable feature and could change in the future.
755
+ >
756
+ > If you already have a custom `getLoadContext` function, you now have to return a `Map` from it. Check the example for more information.
757
+
758
+
684
759
  ### Using WebSockets
685
760
  #### Node
686
761
  This package has a built-in helper to use `@hono/node-ws`
@@ -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;
@@ -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-6GJF2WWC.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,10 @@
1
1
  import { Serve, ServeOptions } from 'bun';
2
2
  import { Env } from 'hono';
3
3
  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';
4
+ import { H as HonoServerOptionsBase, a as WithWebsocket, 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
  type CustomBunServer = Serve & ServeOptions & {
10
10
  websocket?: unknown;
@@ -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-6GJF2WWC.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);
@@ -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-6GJF2WWC.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);
@@ -2,13 +2,13 @@ import { AddressInfo } from 'node:net';
2
2
  import { ServerType } from '@hono/node-server';
3
3
  import { Env, Hono } from 'hono';
4
4
  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';
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 { ServerOptions, createServer } from 'node:http';
8
8
  import { ServerOptions as ServerOptions$2, createServer as createServer$2, SecureServerOptions, createSecureServer } from 'node:http2';
9
9
  import { ServerOptions as ServerOptions$1, createServer as createServer$1 } from 'node:https';
10
- import 'react-router';
11
10
  import 'hono/ws';
11
+ import 'react-router';
12
12
 
13
13
  type createHttpOptions = {
14
14
  serverOptions?: ServerOptions;
@@ -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-6GJF2WWC.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);
@@ -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") {
@@ -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/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,7 +1,3 @@
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";
@@ -37,6 +33,11 @@ function reactRouterHonoServer(options = {}) {
37
33
  if (!pluginConfig) {
38
34
  return;
39
35
  }
36
+ if (pluginConfig.future.unstable_viteEnvironmentApi) {
37
+ console.warn(
38
+ "\x1B[33mThe unstable_viteEnvironmentApi is enabled.\nThis is experimental and may break your build.\x1B[0m\n"
39
+ );
40
+ }
40
41
  if (runtime === "cloudflare" && !config.plugins?.find((p) => p && "name" in p && p.name === "react-router-cloudflare-vite-dev-proxy")) {
41
42
  console.warn(
42
43
  `\x1B[31mMissing cloudflareDevProxy() in your vite.config.ts.
@@ -59,7 +60,7 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
59
60
  noExternal: ["react-router-hono-server"]
60
61
  }
61
62
  };
62
- if (!pluginConfig.isSsrBuild) {
63
+ if (!pluginConfig.future.unstable_viteEnvironmentApi && !pluginConfig.isSsrBuild) {
63
64
  return baseConfig;
64
65
  }
65
66
  let reactRouterBuildFile = pluginConfig.serverBuildFile;
@@ -68,13 +69,12 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
68
69
  }
69
70
  let alias = void 0;
70
71
  if (runtime === "cloudflare") {
71
- const reactVersion = await getReactVersion();
72
+ const reactVersion = await getReactVersion(pluginConfig);
72
73
  alias = {
73
74
  "react-dom/server": reactVersion >= 19 ? "react-dom/server.edge" : "react-dom/server.browser"
74
75
  };
75
76
  }
76
- return {
77
- ...baseConfig,
77
+ const ssrConfig = {
78
78
  resolve: {
79
79
  alias
80
80
  },
@@ -97,6 +97,18 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
97
97
  }
98
98
  }
99
99
  };
100
+ if (pluginConfig.future.unstable_viteEnvironmentApi) {
101
+ return {
102
+ ...baseConfig,
103
+ environments: {
104
+ ssr: ssrConfig
105
+ }
106
+ };
107
+ }
108
+ return {
109
+ ...baseConfig,
110
+ ...ssrConfig
111
+ };
100
112
  },
101
113
  async closeBundle() {
102
114
  if (!pluginConfig || !pluginConfig.isSsrBuild || runtime !== "cloudflare") {
@@ -104,9 +116,19 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
104
116
  }
105
117
  console.log("Cleaning up server exports...");
106
118
  const buildPath = path.join(pluginConfig.rootDirectory, pluginConfig.buildDirectory, "server", "index.js");
107
- let content = await fs.promises.readFile(buildPath, "utf-8");
119
+ let content = await fs.promises.readFile(buildPath, "utf-8").catch((e) => {
120
+ if (e.code === "ENOENT") {
121
+ console.error("\x1B[31m\nThe server was not built\x1B[0m");
122
+ if (pluginConfig?.flag?.force_react_19) {
123
+ console.error(
124
+ "\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"
125
+ );
126
+ }
127
+ }
128
+ throw e;
129
+ });
108
130
  content = content.replace(reactRouterExport, "");
109
- if (await getReactVersion() >= 19) {
131
+ if (await getReactVersion(pluginConfig) >= 19) {
110
132
  content = content.replace(/react-dom\/server\.browser/g, "react-dom/server.edge");
111
133
  }
112
134
  await fs.promises.writeFile(buildPath, content);
@@ -171,6 +193,7 @@ function resolvePluginConfig(config, options) {
171
193
  const serverEntryPoint = options.serverEntryPoint || findDefaultServerEntry(appDirectory);
172
194
  const serverBuildFile = reactRouterConfig.serverBuildFile;
173
195
  const basename = reactRouterConfig.basename;
196
+ const future = reactRouterConfig.future;
174
197
  return {
175
198
  rootDirectory,
176
199
  buildDirectory,
@@ -180,7 +203,9 @@ function resolvePluginConfig(config, options) {
180
203
  serverEntryPoint,
181
204
  dev: options.dev,
182
205
  serverBuildFile,
183
- basename
206
+ basename,
207
+ future,
208
+ flag: isCloudflareOptions(options) ? options.flag : {}
184
209
  };
185
210
  }
186
211
  var warned = false;
@@ -208,6 +233,17 @@ You can also set the \`serverEntryPoint\` option in the reactRouterHonoServer pl
208
233
  }
209
234
  return virtualModuleId;
210
235
  }
236
+ async function getReactVersion(pluginConfig) {
237
+ if (pluginConfig?.flag?.force_react_19) {
238
+ return 19;
239
+ }
240
+ const reactPackage = await import("react");
241
+ const version = reactPackage.default.version || reactPackage.version;
242
+ return Number.parseInt(version.split(".")[0]);
243
+ }
244
+ function isCloudflareOptions(options) {
245
+ return options.runtime === "cloudflare";
246
+ }
211
247
  export {
212
248
  reactRouterHonoServer
213
249
  };
@@ -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.9.0",
3
+ "version": "2.11.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": {
@@ -63,7 +63,8 @@
63
63
  "check": "biome check .",
64
64
  "check:fix": "biome check --fix .",
65
65
  "typecheck": "tsc",
66
- "validate": "npm run check && npm run tsc"
66
+ "validate": "npm run check && npm run tsc",
67
+ "clear-all": "rm -rf node_modules package-lock.json && find ./examples -type d -name 'node_modules' -exec rm -rf {} + && find ./examples -name 'package-lock.json' -exec rm -f {} +"
67
68
  },
68
69
  "author": "",
69
70
  "license": "ISC",
@@ -91,12 +92,12 @@
91
92
  "@cloudflare/workers-types": "^4.20241112.0",
92
93
  "@types/bun": "^1.1.14",
93
94
  "@types/node": "^22.9.3",
94
- "@vitest/coverage-v8": "^2.1.5",
95
+ "@vitest/coverage-v8": "^2.1.9",
95
96
  "lefthook": "^1.8.4",
96
97
  "npm-run-all": "^4.1.5",
97
98
  "tsup": "^8.3.5",
98
99
  "typescript": "^5.7.2",
99
- "vitest": "^2.1.5"
100
+ "vitest": "^2.1.9"
100
101
  },
101
102
  "peerDependencies": {
102
103
  "@cloudflare/workers-types": "^4.20241112.0",