react-router-hono-server 2.0.0 → 2.1.1

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
@@ -32,7 +32,7 @@ It presets a default Hono server config that you can [customize](#options)
32
32
  >
33
33
  > Only works with **Vite**
34
34
  >
35
- > Only works for **node**
35
+ > Only **Node**, **Bun** and **Cloudflare Workers** are supported
36
36
 
37
37
  > [!TIP]
38
38
  > 👨‍🏫 There is some examples in the [examples](./examples) folder. I hope they will help you.
@@ -91,6 +91,77 @@ Ok, by default it works, but you may want to customize the server and use some m
91
91
  >
92
92
  > `reactRouterHonoServer` plugin is looking for them to find your server file.
93
93
 
94
+
95
+ ### Add the Vite plugin
96
+ > [!NOTE]
97
+ > It uses the `reactRouter` plugin to build your app and will automatically load its config.
98
+
99
+ #### Node
100
+ > [!TIP]
101
+ > Check this [example](./examples/react-router) to see how to use it.
102
+
103
+ ```ts
104
+ // vite.config.ts
105
+ import { reactRouter } from "@react-router/dev/vite";
106
+ import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
107
+ import { defineConfig } from "vite";
108
+ import tsconfigPaths from "vite-tsconfig-paths";
109
+
110
+ export default defineConfig({
111
+ plugins: [
112
+ reactRouterHonoServer(), // add this
113
+ reactRouter(),
114
+ tsconfigPaths()
115
+ ],
116
+ });
117
+ ```
118
+
119
+ #### Bun
120
+ > [!TIP]
121
+ > Check this [example](./examples/react-router-bun) to see how to use it.
122
+
123
+ ```ts
124
+ // vite.config.ts
125
+ import { reactRouter } from "@react-router/dev/vite";
126
+ import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
127
+ import { defineConfig } from "vite";
128
+ import tsconfigPaths from "vite-tsconfig-paths";
129
+
130
+ export default defineConfig({
131
+ plugins: [
132
+ reactRouterHonoServer({ runtime: "bun"} ), // add this
133
+ reactRouter(),
134
+ tsconfigPaths()
135
+ ],
136
+ });
137
+ ```
138
+
139
+ #### Cloudflare Workers
140
+ > [!TIP]
141
+ > Check this [example](./examples/react-router-cloudflare) to see how to use it.
142
+
143
+ > [!IMPORTANT]
144
+ > You need to add the `cloudflareDevProxy` plugin to use the Cloudflare Workers runtime on dev.
145
+
146
+
147
+ ```ts
148
+ // vite.config.ts
149
+ import { reactRouter } from "@react-router/dev/vite";
150
+ import { cloudflareDevProxy } from "@react-router/dev/vite/cloudflare"; // add this
151
+ import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
152
+ import { defineConfig } from "vite";
153
+ import tsconfigPaths from "vite-tsconfig-paths";
154
+
155
+ export default defineConfig({
156
+ plugins: [
157
+ cloudflareDevProxy(),
158
+ reactRouterHonoServer({ runtime: "cloudflare"} ), // add this
159
+ reactRouter(),
160
+ tsconfigPaths()
161
+ ],
162
+ });
163
+ ```
164
+
94
165
  ### Create the server
95
166
  > [!TIP]
96
167
  > You can use the CLI to create the server file for you.
@@ -135,38 +206,51 @@ export default await createHonoServer({/* options */});
135
206
  #### I don't like this default
136
207
  No problem, you can define your files wherever you want.
137
208
 
138
- Use the `serverEntryPoint` option of `reactRouterHonoServer` to point to your server file.
209
+ Use the `serverEntryPoint` option of the Vite plugin `reactRouterHonoServer` to point to your server file.
139
210
 
140
- ### Add the Vite plugin (if not already)
141
- ```ts
142
- // vite.config.ts
143
- import { reactRouter } from "@react-router/dev/vite";
144
- import { reactRouterHonoServer } from "react-router-hono-server/dev"; // add this
145
- import { defineConfig } from "vite";
146
- import tsconfigPaths from "vite-tsconfig-paths";
147
211
 
148
- export default defineConfig({
149
- plugins: [
150
- reactRouterHonoServer(), // add this
151
- reactRouter(),
152
- tsconfigPaths()
153
- ],
154
- });
212
+ ### Update your package.json scripts
213
+ ### Node
214
+ It is not an error, you can keep the React Router defaults for `build` and `dev`!
215
+ ```json
216
+ "scripts": {
217
+ "build": "react-router build",
218
+ "dev": "react-router dev",
219
+ "start": "node ./build/server/index.js",
220
+ },
221
+ ```
222
+ ### Bun
223
+ It is not an error, you can keep the React Router defaults for `build`!
224
+ ```json
225
+ "scripts": {
226
+ "build": "react-router build",
227
+ "dev": "bunx --bun vite",
228
+ "start": "bun ./build/server/index.js",
229
+ },
155
230
  ```
156
- > [!NOTE]
157
- > It uses the `reactRouter` plugin to build your app and will automatically load its config.
158
-
159
231
 
160
- ### Update your package.json scripts
232
+ ### Cloudflare
161
233
  It is not an error, you can keep the React Router defaults for `build` and `dev`!
162
234
  ```json
163
235
  "scripts": {
164
236
  "build": "react-router build",
165
237
  "dev": "react-router dev",
166
- "start": "NODE_ENV=production node ./build/server/index.js",
238
+ "start": "wrangler dev",
167
239
  },
168
240
  ```
169
241
 
242
+ #### Wrangler
243
+ Add a file named `wrangler.toml` at the root of your project (close to `package.json`).
244
+
245
+ Adapt the `main` and `assets` fields based on your build output, if you changed them from the defaults.
246
+ ```toml
247
+ workers_dev = true
248
+ name = "my-worker"
249
+ compatibility_date = "2024-11-18"
250
+ main = "./build/server/index.js"
251
+ assets = { directory = "./build/client/" }
252
+ ```
253
+
170
254
  ## How it works
171
255
 
172
256
  This helper works differently depending on the environment.
@@ -179,12 +263,51 @@ You can customize the production server port using the `port` option of `createH
179
263
 
180
264
  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`.
181
265
 
182
- To run the server in production, use `NODE_ENV=production node ./build/server/index.js`.
266
+ To run the server in production, use `node ./build/server/index.js`.
183
267
 
184
268
  That's all!
185
269
 
186
270
  ### Options
271
+
272
+ #### `reactRouterHonoServer` (Vite Plugin)
273
+ ```ts
274
+ type Runtime = "node" | "bun" | "cloudflare";
275
+
276
+ type ReactRouterHonoServerPluginOptions = {
277
+ /**
278
+ * The runtime to use for the server.
279
+ *
280
+ * Defaults to `node`.
281
+ */
282
+ runtime?: Runtime;
283
+ /**
284
+ * The path to the server file, relative to `vite.config.ts`.
285
+ *
286
+ * If it is a folder (`app/server`), it will look for an `index.ts` file.
287
+ *
288
+ * Defaults to `${appDirectory}/server[.ts | /index.ts]` if present.
289
+ *
290
+ * Fallback to a virtual module `virtual:react-router-hono-server/server`.
291
+ */
292
+ serverEntryPoint?: string;
293
+ /**
294
+ * The paths that are not served by the dev-server.
295
+ *
296
+ * Defaults include `appDirectory` content.
297
+ */
298
+ dev?: {
299
+ /**
300
+ * The paths that are not served by the dev-server.
301
+ *
302
+ * Defaults include `appDirectory` content.
303
+ */
304
+ exclude?: (string | RegExp)[];
305
+ };
306
+ };
307
+ ```
308
+
187
309
  #### `createHonoServer`
310
+ ##### All adapters
188
311
  ```ts
189
312
  export type HonoServerOptions<E extends Env = BlankEnv> = {
190
313
  /**
@@ -240,12 +363,6 @@ export type HonoServerOptions<E extends Env = BlankEnv> = {
240
363
  * {@link HonoOptions}
241
364
  */
242
365
  honoOptions?: HonoOptions<E>;
243
- /**
244
- * Customize the node server (ex: using http2)
245
- *
246
- * {@link https://hono.dev/docs/getting-started/nodejs#http2}
247
- */
248
- customNodeServer?: CreateNodeServerOptions;
249
366
  };
250
367
  ```
251
368
 
@@ -259,7 +376,7 @@ Modify the `AppLoadContext` interface used in your app.
259
376
 
260
377
  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.
261
378
 
262
- ##### Example
379
+ ###### Example
263
380
 
264
381
  ```ts
265
382
  // app/server.ts
@@ -297,33 +414,41 @@ export async function loader({ context }: Route.LoaderArgs) {
297
414
  }
298
415
  ```
299
416
 
300
- #### `reactRouterHonoServer`
417
+ ##### Node
301
418
  ```ts
302
- type ReactRouterHonoServerPluginOptions = {
419
+ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
303
420
  /**
304
- * The path to the server file, relative to `vite.config.ts`.
421
+ * Listening listener (production mode only)
305
422
  *
306
- * If it is a folder (`app/server`), it will look for an `index.ts` file.
423
+ * It is called when the server is listening
307
424
  *
308
- * Defaults to `${appDirectory}/server[.ts | /index.ts]` if present.
425
+ * Defaults log the port
426
+ */
427
+ listeningListener?: (info: AddressInfo) => void;
428
+ /**
429
+ * Customize the node server (ex: using http2)
309
430
  *
310
- * Fallback to a virtual module `virtual:react-router-hono-server/server`.
431
+ * {@link https://hono.dev/docs/getting-started/nodejs#http2}
311
432
  */
312
- serverEntryPoint?: string;
433
+ customNodeServer?: CreateNodeServerOptions;
434
+ }
435
+ ```
436
+
437
+ ##### Bun
438
+ ```ts
439
+ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
313
440
  /**
314
- * The paths that are not served by the dev-server.
441
+ * Customize the bun server
315
442
  *
316
- * Defaults include `appDirectory` content.
443
+ * {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
317
444
  */
318
- dev?: {
319
- /**
320
- * The paths that are not served by the dev-server.
321
- *
322
- * Defaults include `appDirectory` content.
323
- */
324
- exclude?: (string | RegExp)[];
325
- };
326
- };
445
+ customBunServer?: Serve & ServeOptions;
446
+ }
447
+ ```
448
+
449
+ ##### Cloudflare Workers
450
+ ```ts
451
+ export interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {}
327
452
  ```
328
453
 
329
454
  ## Middleware
@@ -475,7 +600,7 @@ If you used a custom `buildDirectory` option, check this [example](./examples/re
475
600
  "scripts": {
476
601
  "build": "react-router build",
477
602
  "dev": "react-router dev",
478
- "start": "NODE_ENV=production node ./build/server/index.js",
603
+ "start": "node ./build/server/index.js",
479
604
  },
480
605
  ```
481
606
 
@@ -0,0 +1,107 @@
1
+ import * as bun from 'bun';
2
+ import { Serve, ServeOptions } from 'bun';
3
+ import * as hono from 'hono';
4
+ import { Env } from 'hono';
5
+ import { BlankEnv } from 'hono/types';
6
+ import { H as HonoServerOptionsBase } from '../hono-server-options-base.d-DChVrA1u.mjs';
7
+ import 'hono/hono-base';
8
+ import 'react-router';
9
+
10
+ interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
11
+ /**
12
+ * Customize the bun server
13
+ *
14
+ * {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
15
+ */
16
+ customBunServer?: Serve & ServeOptions;
17
+ }
18
+ /**
19
+ * Create a Hono server
20
+ *
21
+ * @param HonoServerOptions options {@link HonoServerOptions} - The configuration options for the server
22
+ */
23
+ declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptions<E>): Promise<{
24
+ fetch: (request: Request, Env?: {} | E["Bindings"] | undefined, executionCtx?: hono.ExecutionContext) => Response | Promise<Response>;
25
+ port: number;
26
+ development: boolean;
27
+ } | {
28
+ fetch: (request: Request, Env?: {} | E["Bindings"] | undefined, executionCtx?: hono.ExecutionContext) => Response | Promise<Response>;
29
+ port: number;
30
+ development: boolean;
31
+ reusePort?: boolean;
32
+ hostname?: string;
33
+ unix?: never;
34
+ idleTimeout?: number;
35
+ maxRequestBodySize?: number;
36
+ error?: (this: bun.Server, error: bun.ErrorLike) => Response | Promise<Response> | undefined | Promise<undefined>;
37
+ id?: string | null;
38
+ static?: Record<`/${string}`, Response>;
39
+ } | {
40
+ fetch: (request: Request, Env?: {} | E["Bindings"] | undefined, executionCtx?: hono.ExecutionContext) => Response | Promise<Response>;
41
+ port: number;
42
+ development: boolean;
43
+ tls?: bun.TLSOptions | bun.TLSOptions[];
44
+ reusePort?: boolean;
45
+ hostname?: string;
46
+ unix?: never;
47
+ idleTimeout?: number;
48
+ maxRequestBodySize?: number;
49
+ error?: (this: bun.Server, error: bun.ErrorLike) => Response | Promise<Response> | undefined | Promise<undefined>;
50
+ id?: string | null;
51
+ static?: Record<`/${string}`, Response>;
52
+ passphrase?: string;
53
+ dhParamsFile?: string;
54
+ serverName?: string;
55
+ lowMemoryMode?: boolean;
56
+ rejectUnauthorized?: boolean;
57
+ requestCert?: boolean;
58
+ ca?: string | Buffer | bun.BunFile | Array<string | Buffer | bun.BunFile> | undefined;
59
+ cert?: string | Buffer | bun.BunFile | Array<string | Buffer | bun.BunFile> | undefined;
60
+ key?: string | Buffer | bun.BunFile | Array<string | Buffer | bun.BunFile> | undefined;
61
+ secureOptions?: number | undefined;
62
+ keyFile?: string;
63
+ certFile?: string;
64
+ caFile?: string;
65
+ } | {
66
+ fetch: (request: Request, Env?: {} | E["Bindings"] | undefined, executionCtx?: hono.ExecutionContext) => Response | Promise<Response>;
67
+ port: number;
68
+ development: boolean;
69
+ hostname?: string;
70
+ websocket: bun.WebSocketHandler<undefined>;
71
+ maxRequestBodySize?: number;
72
+ error?: (this: bun.Server, error: bun.ErrorLike) => Response | Promise<Response> | undefined | Promise<undefined>;
73
+ id?: string | null;
74
+ static?: Record<`/${string}`, Response>;
75
+ reusePort?: boolean;
76
+ unix?: never;
77
+ idleTimeout?: number;
78
+ } | {
79
+ fetch: (request: Request, Env?: {} | E["Bindings"] | undefined, executionCtx?: hono.ExecutionContext) => Response | Promise<Response>;
80
+ port: number;
81
+ development: boolean;
82
+ unix?: never;
83
+ tls?: bun.TLSOptions | bun.TLSOptions[];
84
+ hostname?: string;
85
+ websocket: bun.WebSocketHandler<undefined>;
86
+ maxRequestBodySize?: number;
87
+ error?: (this: bun.Server, error: bun.ErrorLike) => Response | Promise<Response> | undefined | Promise<undefined>;
88
+ id?: string | null;
89
+ static?: Record<`/${string}`, Response>;
90
+ passphrase?: string;
91
+ dhParamsFile?: string;
92
+ serverName?: string;
93
+ lowMemoryMode?: boolean;
94
+ rejectUnauthorized?: boolean;
95
+ requestCert?: boolean;
96
+ ca?: string | Buffer | bun.BunFile | Array<string | Buffer | bun.BunFile> | undefined;
97
+ cert?: string | Buffer | bun.BunFile | Array<string | Buffer | bun.BunFile> | undefined;
98
+ key?: string | Buffer | bun.BunFile | Array<string | Buffer | bun.BunFile> | undefined;
99
+ secureOptions?: number | undefined;
100
+ keyFile?: string;
101
+ certFile?: string;
102
+ caFile?: string;
103
+ reusePort?: boolean;
104
+ idleTimeout?: number;
105
+ }>;
106
+
107
+ export { type HonoServerOptions, createHonoServer };
@@ -0,0 +1,57 @@
1
+ import {
2
+ cache
3
+ } from "../chunk-ENK5WJB4.mjs";
4
+
5
+ // src/adapters/bun.ts
6
+ import { Hono } from "hono";
7
+ import { serveStatic } from "hono/bun";
8
+ import { createMiddleware } from "hono/factory";
9
+ import { logger } from "hono/logger";
10
+ import { createRequestHandler } from "react-router";
11
+ async function createHonoServer(options = {}) {
12
+ const mergedOptions = {
13
+ ...options,
14
+ port: options.port || Number(options.customBunServer?.port) || Number(process.env.PORT) || 3e3,
15
+ defaultLogger: options.defaultLogger ?? true
16
+ };
17
+ const mode = import.meta.env.MODE;
18
+ const PRODUCTION = mode === "production";
19
+ const server = new Hono(mergedOptions.honoOptions);
20
+ const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
21
+ server.use(
22
+ `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
23
+ cache(60 * 60 * 24 * 365),
24
+ // 1 year
25
+ serveStatic({ root: clientBuildPath })
26
+ );
27
+ server.use("*", cache(60 * 60), serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" }));
28
+ if (mergedOptions.defaultLogger) {
29
+ server.use("*", logger());
30
+ }
31
+ if (mergedOptions.configure) {
32
+ await mergedOptions.configure(server);
33
+ }
34
+ server.use(async (c, next) => {
35
+ const build = await import(
36
+ // @ts-expect-error - Virtual module provided by React Router at build time
37
+ "virtual:react-router/server-build"
38
+ );
39
+ return createMiddleware(async (c2) => {
40
+ const requestHandler = createRequestHandler(build, mode);
41
+ const loadContext = mergedOptions.getLoadContext?.(c2, { build, mode });
42
+ return requestHandler(c2.req.raw, loadContext instanceof Promise ? await loadContext : loadContext);
43
+ })(c, next);
44
+ });
45
+ if (!PRODUCTION) {
46
+ console.log("\u{1F6A7} Running in development mode");
47
+ }
48
+ return {
49
+ ...mergedOptions.customBunServer,
50
+ fetch: server.fetch,
51
+ port: mergedOptions.port,
52
+ development: !PRODUCTION
53
+ };
54
+ }
55
+ export {
56
+ createHonoServer
57
+ };
@@ -0,0 +1,17 @@
1
+ import * as hono_types from 'hono/types';
2
+ import { BlankEnv } from 'hono/types';
3
+ import { Env, Hono } from 'hono';
4
+ import { H as HonoServerOptionsBase } from '../hono-server-options-base.d-DChVrA1u.mjs';
5
+ import 'hono/hono-base';
6
+ import 'react-router';
7
+
8
+ interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {
9
+ }
10
+ /**
11
+ * Create a Hono server
12
+ *
13
+ * @param config {@link HonoServerOptions} - The configuration options for the server
14
+ */
15
+ declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptions<E>): Promise<Hono<E, hono_types.BlankSchema, "/">>;
16
+
17
+ export { type HonoServerOptions, createHonoServer };
@@ -0,0 +1,38 @@
1
+ // src/adapters/cloudflare.ts
2
+ import { Hono } from "hono";
3
+ import { createMiddleware } from "hono/factory";
4
+ import { logger } from "hono/logger";
5
+ import { createRequestHandler } from "react-router";
6
+ async function createHonoServer(options = {}) {
7
+ const mergedOptions = {
8
+ ...options,
9
+ defaultLogger: options.defaultLogger ?? true
10
+ };
11
+ const mode = import.meta.env.MODE;
12
+ const PRODUCTION = mode === "production";
13
+ const server = new Hono(mergedOptions.honoOptions);
14
+ if (mergedOptions.defaultLogger) {
15
+ server.use("*", logger());
16
+ }
17
+ if (mergedOptions.configure) {
18
+ await mergedOptions.configure(server);
19
+ }
20
+ server.use(async (c, next) => {
21
+ const build = await import(
22
+ // @ts-expect-error - Virtual module provided by React Router at build time
23
+ "virtual:react-router/server-build"
24
+ );
25
+ return createMiddleware(async (c2) => {
26
+ const requestHandler = createRequestHandler(build, mode);
27
+ const loadContext = mergedOptions.getLoadContext?.(c2, { build, mode });
28
+ return requestHandler(c2.req.raw, loadContext instanceof Promise ? await loadContext : loadContext);
29
+ })(c, next);
30
+ });
31
+ if (!PRODUCTION) {
32
+ console.log("\u{1F6A7} Running in development mode");
33
+ }
34
+ return server;
35
+ }
36
+ export {
37
+ createHonoServer
38
+ };
@@ -0,0 +1,57 @@
1
+ import * as hono_types from 'hono/types';
2
+ import { BlankEnv } from 'hono/types';
3
+ import { AddressInfo } from 'node:net';
4
+ import { Env, Hono } from 'hono';
5
+ import { H as HonoServerOptionsBase } from '../hono-server-options-base.d-DChVrA1u.mjs';
6
+ import { ServerOptions, createServer } from 'node:http';
7
+ import { ServerOptions as ServerOptions$2, createServer as createServer$2, SecureServerOptions, createSecureServer } from 'node:http2';
8
+ import { ServerOptions as ServerOptions$1, createServer as createServer$1 } from 'node:https';
9
+ import 'hono/hono-base';
10
+ import 'react-router';
11
+
12
+ type createHttpOptions = {
13
+ serverOptions?: ServerOptions;
14
+ createServer?: typeof createServer;
15
+ };
16
+ type createHttpsOptions = {
17
+ serverOptions?: ServerOptions$1;
18
+ createServer?: typeof createServer$1;
19
+ };
20
+ type createHttp2Options = {
21
+ serverOptions?: ServerOptions$2;
22
+ createServer?: typeof createServer$2;
23
+ };
24
+ type createSecureHttp2Options = {
25
+ serverOptions?: SecureServerOptions;
26
+ createServer?: typeof createSecureServer;
27
+ };
28
+ type CreateNodeServerOptions =
29
+ | createHttpOptions
30
+ | createHttpsOptions
31
+ | createHttp2Options
32
+ | createSecureHttp2Options;
33
+
34
+ interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
35
+ /**
36
+ * Listening listener (production mode only)
37
+ *
38
+ * It is called when the server is listening
39
+ *
40
+ * Defaults log the port
41
+ */
42
+ listeningListener?: (info: AddressInfo) => void;
43
+ /**
44
+ * Customize the node server (ex: using http2)
45
+ *
46
+ * {@link https://hono.dev/docs/getting-started/nodejs#http2}
47
+ */
48
+ customNodeServer?: CreateNodeServerOptions;
49
+ }
50
+ /**
51
+ * Create a Hono server
52
+ *
53
+ * @param config {@link HonoServerOptions} - The configuration options for the server
54
+ */
55
+ declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptions<E>): Promise<Hono<E, hono_types.BlankSchema, "/">>;
56
+
57
+ export { type HonoServerOptions, createHonoServer };
@@ -1,46 +1,25 @@
1
1
  import {
2
2
  cache
3
- } from "./chunk-ENK5WJB4.mjs";
3
+ } from "../chunk-ENK5WJB4.mjs";
4
4
 
5
- // src/node.ts
5
+ // src/adapters/node.ts
6
6
  import { serve } from "@hono/node-server";
7
7
  import { serveStatic } from "@hono/node-server/serve-static";
8
8
  import { Hono } from "hono";
9
9
  import { createMiddleware } from "hono/factory";
10
10
  import { logger } from "hono/logger";
11
11
  import { createRequestHandler } from "react-router";
12
-
13
- // src/utils.ts
14
- var envs = ["test", "development", "production"];
15
- function getMode() {
16
- const NODE_ENV = process.env.NODE_ENV?.toLowerCase();
17
- if (!NODE_ENV || !envs.includes(NODE_ENV)) {
18
- throw new Error(
19
- `NODE_ENV is not set or is not valid: ${NODE_ENV}. Please set it to one of the following: ${envs.join(", ")}`
20
- );
21
- }
22
- return NODE_ENV;
23
- }
24
-
25
- // src/node.ts
26
- var defaultOptions = {
27
- defaultLogger: true,
28
- port: Number(process.env.PORT) || 3e3,
29
- listeningListener: (info) => {
30
- console.log(`\u{1F680} Server started on port ${info.port}`);
31
- console.log(`\u{1F30D} http://127.0.0.1:${info.port}`);
32
- },
33
- getLoadContext() {
34
- return {};
35
- }
36
- };
37
12
  async function createHonoServer(options = {}) {
38
13
  const mergedOptions = {
39
- ...defaultOptions,
14
+ listeningListener: (info) => {
15
+ console.log(`\u{1F680} Server started on port ${info.port}`);
16
+ console.log(`\u{1F30D} http://127.0.0.1:${info.port}`);
17
+ },
40
18
  ...options,
19
+ port: options.port || Number(process.env.PORT) || 3e3,
41
20
  defaultLogger: options.defaultLogger ?? true
42
21
  };
43
- const mode = getMode();
22
+ const mode = import.meta.env.MODE;
44
23
  const PRODUCTION = mode === "production";
45
24
  const server = new Hono(mergedOptions.honoOptions);
46
25
  const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
package/dist/cli.mjs CHANGED
@@ -3,8 +3,18 @@
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { command, run } from "@drizzle-team/brocli";
6
+ var runtimeRegex = /runtime:\s*(['"])([^'"]*)\1/;
7
+ function guessRuntime() {
8
+ try {
9
+ const viteConfig = fs.readFileSync(path.resolve(process.cwd(), "vite.config.ts"), "utf-8");
10
+ return viteConfig.match(runtimeRegex)?.[2] || "node";
11
+ } catch {
12
+ return "node";
13
+ }
14
+ }
15
+ var runtime = guessRuntime();
6
16
  var serverFile = `// generated by react-router-hono-server/dev
7
- import { createHonoServer } from "react-router-hono-server/node";
17
+ import { createHonoServer } from "react-router-hono-server/${runtime}";
8
18
 
9
19
  export default await createHonoServer();`;
10
20
  var file = command({
package/dist/dev.d.mts CHANGED
@@ -1,6 +1,14 @@
1
+ import { DevServerOptions } from '@hono/vite-dev-server';
1
2
  import { Plugin } from 'vite';
2
3
 
4
+ type Runtime = "node" | "bun" | "cloudflare";
3
5
  type ReactRouterHonoServerPluginOptions = {
6
+ /**
7
+ * The runtime to use for the server.
8
+ *
9
+ * Defaults to `node`.
10
+ */
11
+ runtime?: Runtime;
4
12
  /**
5
13
  * The path to the server file, relative to `vite.config.ts`.
6
14
  *
@@ -22,7 +30,7 @@ type ReactRouterHonoServerPluginOptions = {
22
30
  *
23
31
  * Defaults include `appDirectory` content.
24
32
  */
25
- exclude?: (string | RegExp)[];
33
+ exclude?: DevServerOptions["exclude"];
26
34
  };
27
35
  };
28
36
  declare function reactRouterHonoServer(options?: ReactRouterHonoServerPluginOptions): Plugin;
package/dist/dev.mjs CHANGED
@@ -2,8 +2,11 @@
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import honoDevServer from "@hono/vite-dev-server";
5
+ import bunAdapter from "@hono/vite-dev-server/bun";
6
+ import cloudflareAdapter from "@hono/vite-dev-server/cloudflare";
5
7
  var virtualModuleId = "\0virtual:react-router-hono-server/server";
6
8
  function reactRouterHonoServer(options = {}) {
9
+ const runtime = options.runtime || "node";
7
10
  let pluginConfig;
8
11
  let devServerPlugin;
9
12
  return {
@@ -18,7 +21,7 @@ function reactRouterHonoServer(options = {}) {
18
21
  if (id === virtualModuleId) {
19
22
  return `
20
23
  // generated by react-router-hono-server/dev
21
- import { createHonoServer } from "react-router-hono-server/node";
24
+ import { createHonoServer } from "react-router-hono-server/${runtime}";
22
25
 
23
26
  export default await createHonoServer();
24
27
  `;
@@ -29,6 +32,14 @@ function reactRouterHonoServer(options = {}) {
29
32
  if (!pluginConfig) {
30
33
  return;
31
34
  }
35
+ if (runtime === "cloudflare" && !config.plugins?.find((p) => p && "name" in p && p.name === "react-router-cloudflare-vite-dev-proxy")) {
36
+ console.error(
37
+ `\x1B[31mMissing cloudflareDevProxy() in your vite.config.ts.
38
+ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router/dev/vite/cloudflare";\x1B[0m
39
+ `
40
+ );
41
+ throw new Error("Missing mandatory plugin cloudflareDevProxy() in vite.config.ts");
42
+ }
32
43
  const baseConfig = {
33
44
  // Define environment variables that are hot-swapped during development and SSR build
34
45
  define: {
@@ -36,6 +47,7 @@ function reactRouterHonoServer(options = {}) {
36
47
  "import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR": JSON.stringify(pluginConfig.assetsDir)
37
48
  },
38
49
  ssr: {
50
+ target: runtime === "cloudflare" ? "webworker" : void 0,
39
51
  // Ensure our package is not externalized during SSR build
40
52
  // This is necessary because we are using a virtual import to load the React Router server entry point
41
53
  noExternal: ["react-router-hono-server"]
@@ -61,7 +73,15 @@ function reactRouterHonoServer(options = {}) {
61
73
  if (devServerPlugin) {
62
74
  return;
63
75
  }
76
+ let adapter;
77
+ if (runtime === "bun") {
78
+ adapter = bunAdapter;
79
+ }
80
+ if (runtime === "cloudflare") {
81
+ adapter = cloudflareAdapter;
82
+ }
64
83
  devServerPlugin = honoDevServer({
84
+ adapter,
65
85
  injectClientScript: false,
66
86
  entry: pluginConfig.serverEntryPoint,
67
87
  export: "default",
@@ -0,0 +1,54 @@
1
+ import { Env, Hono, Context } from 'hono';
2
+ import { HonoOptions } from 'hono/hono-base';
3
+ import { BlankEnv } from 'hono/types';
4
+ import { ServerBuild, AppLoadContext } from 'react-router';
5
+
6
+ interface HonoServerOptionsBase<E extends Env = BlankEnv> {
7
+ /**
8
+ * Enable the default logger
9
+ *
10
+ * Defaults to `true`
11
+ */
12
+ defaultLogger?: boolean;
13
+ /**
14
+ * The port to start the server on
15
+ *
16
+ * Defaults to `process.env.PORT || 3000`
17
+ */
18
+ port?: number;
19
+ /**
20
+ * Customize the Hono server, for example, adding middleware
21
+ *
22
+ * It is applied after the default middleware and before the React Router middleware
23
+ */
24
+ configure?: <E extends Env = BlankEnv>(server: Hono<E>) => Promise<void> | void;
25
+ /**
26
+ * Augment the React Router AppLoadContext
27
+ *
28
+ * Don't forget to declare the AppLoadContext in your app, next to where you create the Hono server
29
+ *
30
+ * ```ts
31
+ * declare module "react-router" {
32
+ * interface AppLoadContext {
33
+ * // Add your custom context here
34
+ * whatever: string;
35
+ * }
36
+ * }
37
+ * ```
38
+ */
39
+ getLoadContext?: (
40
+ c: Context,
41
+ options: {
42
+ build: ServerBuild;
43
+ mode: string;
44
+ }
45
+ ) => Promise<AppLoadContext> | AppLoadContext;
46
+ /**
47
+ * Hono constructor options
48
+ *
49
+ * {@link HonoOptions}
50
+ */
51
+ honoOptions?: HonoOptions<E>;
52
+ }
53
+
54
+ export type { HonoServerOptionsBase as H };
package/package.json CHANGED
@@ -1,13 +1,27 @@
1
1
  {
2
2
  "name": "react-router-hono-server",
3
- "version": "2.0.0",
4
- "description": "This package includes helper function to create an Hono app in your entry.server.tsx file. It allows you to customize your server.",
3
+ "version": "2.1.1",
4
+ "description": "The Vite plugin you need to create a Hono server for your React Router app in less than 10 seconds.",
5
5
  "exports": {
6
6
  "./node": {
7
7
  "import": {
8
- "import": "./dist/node.mjs",
9
- "types": "./dist/node.d.mts",
10
- "default": "./dist/node.mjs"
8
+ "import": "./dist/adapters/node.mjs",
9
+ "types": "./dist/adapters/node.d.mts",
10
+ "default": "./dist/adapters/node.mjs"
11
+ }
12
+ },
13
+ "./bun": {
14
+ "import": {
15
+ "import": "./dist/adapters/bun.mjs",
16
+ "types": "./dist/adapters/bun.d.mts",
17
+ "default": "./dist/adapters/bun.mjs"
18
+ }
19
+ },
20
+ "./cloudflare": {
21
+ "import": {
22
+ "import": "./dist/adapters/cloudflare.mjs",
23
+ "types": "./dist/adapters/cloudflare.d.mts",
24
+ "default": "./dist/adapters/cloudflare.mjs"
11
25
  }
12
26
  },
13
27
  "./dev": {
@@ -61,9 +75,11 @@
61
75
  },
62
76
  "devDependencies": {
63
77
  "@biomejs/biome": "^1.9.4",
78
+ "@types/bun": "^1.1.14",
64
79
  "@types/node": "^22.9.3",
65
80
  "@vitest/coverage-v8": "^2.1.5",
66
81
  "lefthook": "^1.8.4",
82
+ "miniflare": "^3.20241106.1",
67
83
  "npm-run-all": "^4.1.5",
68
84
  "tsup": "^8.3.5",
69
85
  "typescript": "^5.7.2",
package/dist/node.d.mts DELETED
@@ -1,94 +0,0 @@
1
- import * as hono_types from 'hono/types';
2
- import { BlankEnv } from 'hono/types';
3
- import { AddressInfo } from 'node:net';
4
- import { Env, Hono, Context } from 'hono';
5
- import { HonoOptions } from 'hono/hono-base';
6
- import { ServerBuild, AppLoadContext } from 'react-router';
7
- import { ServerOptions, createServer } from 'node:http';
8
- import { ServerOptions as ServerOptions$2, createServer as createServer$2, SecureServerOptions, createSecureServer } from 'node:http2';
9
- import { ServerOptions as ServerOptions$1, createServer as createServer$1 } from 'node:https';
10
-
11
- type createHttpOptions = {
12
- serverOptions?: ServerOptions;
13
- createServer?: typeof createServer;
14
- };
15
- type createHttpsOptions = {
16
- serverOptions?: ServerOptions$1;
17
- createServer?: typeof createServer$1;
18
- };
19
- type createHttp2Options = {
20
- serverOptions?: ServerOptions$2;
21
- createServer?: typeof createServer$2;
22
- };
23
- type createSecureHttp2Options = {
24
- serverOptions?: SecureServerOptions;
25
- createServer?: typeof createSecureServer;
26
- };
27
- type CreateNodeServerOptions = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;
28
-
29
- type HonoServerOptions<E extends Env = BlankEnv> = {
30
- /**
31
- * Enable the default logger
32
- *
33
- * Defaults to `true`
34
- */
35
- defaultLogger?: boolean;
36
- /**
37
- * The port to start the server on
38
- *
39
- * Defaults to `process.env.PORT || 3000`
40
- */
41
- port?: number;
42
- /**
43
- * Customize the Hono server, for example, adding middleware
44
- *
45
- * It is applied after the default middleware and before the React Router middleware
46
- */
47
- configure?: <E extends Env = BlankEnv>(server: Hono<E>) => Promise<void> | void;
48
- /**
49
- * Augment the React Router AppLoadContext
50
- *
51
- * Don't forget to declare the AppLoadContext in your app, next to where you create the Hono server
52
- *
53
- * ```ts
54
- * declare module "react-router" {
55
- * interface AppLoadContext {
56
- * // Add your custom context here
57
- * whatever: string;
58
- * }
59
- * }
60
- * ```
61
- */
62
- getLoadContext?: (c: Context, options: {
63
- build: ServerBuild;
64
- mode: "development" | "production" | "test";
65
- }) => Promise<AppLoadContext> | AppLoadContext;
66
- /**
67
- * Listening listener (production mode only)
68
- *
69
- * It is called when the server is listening
70
- *
71
- * Defaults log the port
72
- */
73
- listeningListener?: (info: AddressInfo) => void;
74
- /**
75
- * Hono constructor options
76
- *
77
- * {@link HonoOptions}
78
- */
79
- honoOptions?: HonoOptions<E>;
80
- /**
81
- * Customize the node server (ex: using http2)
82
- *
83
- * {@link https://hono.dev/docs/getting-started/nodejs#http2}
84
- */
85
- customNodeServer?: CreateNodeServerOptions;
86
- };
87
- /**
88
- * Create a Hono server
89
- *
90
- * @param config {@link HonoServerOptions} - The configuration options for the server
91
- */
92
- declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptions<E>): Promise<Hono<E, hono_types.BlankSchema, "/">>;
93
-
94
- export { type HonoServerOptions, createHonoServer };