react-router-hono-server 2.1.2 → 2.2.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
@@ -101,7 +101,7 @@ Ok, by default it works, but you may want to customize the server and use some m
101
101
 
102
102
  #### Node
103
103
  > [!TIP]
104
- > Check this [example](./examples/react-router) to see how to use it.
104
+ > Check this [example](./examples/node/simple/) to see how to use it.
105
105
 
106
106
  ```ts
107
107
  // vite.config.ts
@@ -121,7 +121,7 @@ export default defineConfig({
121
121
 
122
122
  #### Bun
123
123
  > [!TIP]
124
- > Check this [example](./examples/react-router-bun) to see how to use it.
124
+ > Check this [example](./examples/bun/simple/) to see how to use it.
125
125
 
126
126
  ```ts
127
127
  // vite.config.ts
@@ -141,7 +141,7 @@ export default defineConfig({
141
141
 
142
142
  #### Cloudflare Workers
143
143
  > [!TIP]
144
- > Check this [example](./examples/react-router-cloudflare) to see how to use it.
144
+ > Check this [example](./examples/cloudflare/simple/) to see how to use it.
145
145
 
146
146
  > [!IMPORTANT]
147
147
  > You need to add the `cloudflareDevProxy` plugin to use the Cloudflare Workers runtime on dev.
@@ -313,6 +313,12 @@ type ReactRouterHonoServerPluginOptions = {
313
313
  ##### All adapters
314
314
  ```ts
315
315
  export type HonoServerOptions<E extends Env = BlankEnv> = {
316
+ /**
317
+ * Hono app to use
318
+ *
319
+ * {@link Hono}
320
+ */
321
+ app?: Hono<E>;
316
322
  /**
317
323
  * Enable the default logger
318
324
  *
@@ -360,12 +366,6 @@ export type HonoServerOptions<E extends Env = BlankEnv> = {
360
366
  * Defaults log the port
361
367
  */
362
368
  listeningListener?: (info: AddressInfo) => void;
363
- /**
364
- * Hono constructor options
365
- *
366
- * {@link HonoOptions}
367
- */
368
- honoOptions?: HonoOptions<E>;
369
369
  };
370
370
  ```
371
371
 
@@ -434,6 +434,14 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
434
434
  * {@link https://hono.dev/docs/getting-started/nodejs#http2}
435
435
  */
436
436
  customNodeServer?: CreateNodeServerOptions;
437
+ /**
438
+ * Callback executed just after `serve` from `@hono/node-server`
439
+ *
440
+ * **Only applied to production mode**
441
+ *
442
+ * For example, you can use this to bind `@hono/node-ws`'s `injectWebSocket`
443
+ */
444
+ onServe?: (server: ServerType) => void;
437
445
  }
438
446
  ```
439
447
 
@@ -533,6 +541,110 @@ export default await createHonoServer({
533
541
  });
534
542
  ```
535
543
 
544
+ ### Using WebSockets
545
+ #### Node
546
+ This package has a built-in helper to use `@hono/node-ws`
547
+
548
+ > [!TIP]
549
+ > Check this [example](./examples/node/websocket/) to see how to use it.
550
+
551
+ ```ts
552
+ import type { WSContext } from "hono/ws";
553
+ import { createHonoServer } from "react-router-hono-server/node";
554
+
555
+ // Store connected clients
556
+ const clients = new Set<WSContext>();
557
+
558
+ export default await createHonoServer({
559
+ useWebSocket: true,
560
+ // 👆 Unlock this 👇 from @hono/node-ws
561
+ configure: (app, { upgradeWebSocket }) => {
562
+ app.get(
563
+ "/ws",
564
+ upgradeWebSocket((c) => ({
565
+ // https://hono.dev/helpers/websocket
566
+ onOpen(_, ws) {
567
+ console.log("New connection ⬆️");
568
+ clients.add(ws);
569
+ },
570
+ onMessage(event, ws) {
571
+ console.log("Context", c.req.header("Cookie"));
572
+ console.log("Event", event);
573
+ console.log(`Message from client: ${event.data}`);
574
+ // Broadcast to all clients except sender
575
+ clients.forEach((client) => {
576
+ if (client.readyState === 1) {
577
+ client.send(`${event.data}`);
578
+ }
579
+ });
580
+ },
581
+ onClose(_, ws) {
582
+ console.log("Connection closed");
583
+ clients.delete(ws);
584
+ },
585
+ }))
586
+ );
587
+ },
588
+ });
589
+ ```
590
+
591
+ #### Bun
592
+ This package has a built-in helper to use `hono/bun` in prod and `@hono/node-ws` in dev
593
+
594
+ > [!TIP]
595
+ > Check this [example](./examples/bun/websocket/) to see how to use it.
596
+
597
+ ```ts
598
+ import { WSContext } from "hono/ws";
599
+ import { createHonoServer } from "react-router-hono-server/bun";
600
+
601
+ // Store connected clients
602
+ const clients = new Set<WSContext>();
603
+
604
+ export default await createHonoServer({
605
+ useWebSocket: true,
606
+ // 👆 Unlock this 👇 from @hono/node-ws in dev, hono/bun in prod
607
+ configure(app, { upgradeWebSocket }) {
608
+ app.get(
609
+ "/ws",
610
+ upgradeWebSocket((c) => ({
611
+ // https://hono.dev/helpers/websocket
612
+ onOpen(_, ws) {
613
+ console.log("New connection 🔥");
614
+ clients.add(ws);
615
+ },
616
+ onMessage(event, ws) {
617
+ console.log("Context", c.req.header("Cookie"));
618
+ console.log("Event", event);
619
+ console.log(`Message from client: ${event.data}`);
620
+ // Broadcast to all clients except sender
621
+ clients.forEach((client) => {
622
+ if (client.readyState === 1) {
623
+ client.send(`${event.data}`);
624
+ }
625
+ });
626
+ },
627
+ onClose(_, ws) {
628
+ console.log("Connection closed");
629
+ clients.delete(ws);
630
+ },
631
+ }))
632
+ );
633
+ },
634
+ });
635
+ ```
636
+
637
+ #### Cloudflare Workers
638
+ Cloudflare requires a different approach to WebSockets, based on Durable Objects.
639
+
640
+ > [!TIP]
641
+ > Check this [example](./examples/cloudflare/websocket/) to see how to use it.
642
+
643
+ > [!IMPORTANT]
644
+ > For now, HMR is not supported in Cloudflare Workers. Will try to come back to it later.
645
+ >
646
+ > Work in progress on Cloudflare team: https://github.com/flarelabs-net/vite-plugin-cloudflare
647
+
536
648
  ### Migrate from v1
537
649
  _You should not expect any breaking changes._
538
650
 
@@ -594,9 +706,9 @@ Many options are gone or have changed.
594
706
  ##### You used `buildEnd` from `remix()` plugin or a custom `buildDirectory` option
595
707
  You may know that it has been moved to `react-router.config.ts` (see [here](https://reactrouter.com/upgrading/remix#5-add-a-react-router-config) for more information).
596
708
 
597
- If you used this hook for Sentry, check this [example](./examples/react-router-sentry/react-router.config.ts) to see how to migrate.
709
+ If you used this hook for Sentry, check this [example](./examples/node/with-sentry/react-router.config.ts) to see how to migrate.
598
710
 
599
- If you used a custom `buildDirectory` option, check this [example](./examples/react-router-custom-build/react-router.config.ts) to see how to migrate.
711
+ If you used a custom `buildDirectory` option, check this [example](./examples/node/custom-build/react-router.config.ts) to see how to migrate.
600
712
 
601
713
  #### Update your package.json scripts
602
714
  ```json
@@ -0,0 +1,31 @@
1
+ import { Serve, ServeOptions } from 'bun';
2
+ import { Env } from 'hono';
3
+ import { BlankEnv } from 'hono/types';
4
+ import { W as WithWebsocket, a as WithoutWebsocket, H as HonoServerOptionsBase } from '../hono-server-options-base.d-XkJeTOq3.js';
5
+ import 'hono/hono-base';
6
+ import 'hono/ws';
7
+ import 'react-router';
8
+
9
+ type CustomBunServer = Serve & ServeOptions & {
10
+ websocket?: unknown;
11
+ };
12
+ interface HonoBunServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
13
+ /**
14
+ * Customize the bun server
15
+ *
16
+ * {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
17
+ */
18
+ customBunServer?: Partial<CustomBunServer>;
19
+ }
20
+ type HonoServerOptionsWithWebSocket<E extends Env = BlankEnv> = HonoBunServerOptions<E> & WithWebsocket<E>;
21
+ type HonoServerOptionsWithoutWebSocket<E extends Env = BlankEnv> = HonoBunServerOptions<E> & WithoutWebsocket<E>;
22
+ type HonoServerOptions<E extends Env = BlankEnv> = HonoServerOptionsWithWebSocket<E> | HonoServerOptionsWithoutWebSocket<E>;
23
+ /**
24
+ * Create a Hono server
25
+ *
26
+ * @param HonoServerOptions options {@link HonoServerOptions} - The configuration options for the server
27
+ */
28
+ declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptionsWithoutWebSocket<E>): Promise<CustomBunServer>;
29
+ declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptionsWithWebSocket<E>): Promise<CustomBunServer>;
30
+
31
+ export { type HonoServerOptions, createHonoServer };
@@ -1,6 +1,11 @@
1
+ import {
2
+ cleanUpgradeListeners,
3
+ createWebSocket,
4
+ patchUpgradeListener
5
+ } from "../chunk-27A6I7NN.js";
1
6
  import {
2
7
  cache
3
- } from "../chunk-ENK5WJB4.mjs";
8
+ } from "../chunk-V3H4JZ4H.js";
4
9
 
5
10
  // src/adapters/bun.ts
6
11
  import { Hono } from "hono";
@@ -8,30 +13,36 @@ import { serveStatic } from "hono/bun";
8
13
  import { createMiddleware } from "hono/factory";
9
14
  import { logger } from "hono/logger";
10
15
  import { createRequestHandler } from "react-router";
11
- async function createHonoServer(options = {}) {
16
+ async function createHonoServer(options) {
12
17
  const mergedOptions = {
13
18
  ...options,
14
- port: options.port || Number(options.customBunServer?.port) || Number(process.env.PORT) || 3e3,
15
- defaultLogger: options.defaultLogger ?? true
19
+ port: options?.port || Number(options?.customBunServer?.port) || Number(process.env.PORT) || 3e3,
20
+ defaultLogger: options?.defaultLogger ?? true
16
21
  };
17
- const mode = import.meta.env.MODE;
22
+ const mode = import.meta.env.MODE || "production";
18
23
  const PRODUCTION = mode === "production";
19
- const server = new Hono(mergedOptions.honoOptions);
24
+ const app = new Hono(mergedOptions.honoOptions || mergedOptions.app);
20
25
  const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
21
- server.use(
26
+ const { upgradeWebSocket, injectWebSocket } = await createWebSocket({
27
+ app,
28
+ enabled: mergedOptions.useWebSocket ?? false
29
+ });
30
+ app.use(
22
31
  `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
23
32
  cache(60 * 60 * 24 * 365),
24
33
  // 1 year
25
34
  serveStatic({ root: clientBuildPath })
26
35
  );
27
- server.use("*", cache(60 * 60), serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" }));
36
+ app.use("*", cache(60 * 60), serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" }));
28
37
  if (mergedOptions.defaultLogger) {
29
- server.use("*", logger());
38
+ app.use("*", logger());
30
39
  }
31
- if (mergedOptions.configure) {
32
- await mergedOptions.configure(server);
40
+ if (mergedOptions.useWebSocket) {
41
+ await mergedOptions.configure(app, { upgradeWebSocket });
42
+ } else {
43
+ await mergedOptions.configure?.(app);
33
44
  }
34
- server.use(async (c, next) => {
45
+ app.use(async (c, next) => {
35
46
  const build = await import(
36
47
  // @ts-expect-error - Virtual module provided by React Router at build time
37
48
  "virtual:react-router/server-build"
@@ -42,15 +53,22 @@ async function createHonoServer(options = {}) {
42
53
  return requestHandler(c2.req.raw, loadContext instanceof Promise ? await loadContext : loadContext);
43
54
  })(c, next);
44
55
  });
45
- if (!PRODUCTION) {
46
- console.log("\u{1F6A7} Running in development mode");
47
- }
48
- return {
56
+ let server = {
49
57
  ...mergedOptions.customBunServer,
50
- fetch: server.fetch,
58
+ fetch: app.fetch,
51
59
  port: mergedOptions.port,
52
60
  development: !PRODUCTION
53
61
  };
62
+ if (PRODUCTION) {
63
+ server = injectWebSocket(server);
64
+ } else if (globalThis.__viteDevServer?.httpServer) {
65
+ const httpServer = globalThis.__viteDevServer.httpServer;
66
+ cleanUpgradeListeners(httpServer);
67
+ injectWebSocket(httpServer);
68
+ patchUpgradeListener(httpServer);
69
+ console.log("\u{1F6A7} Running in development mode");
70
+ }
71
+ return server;
54
72
  }
55
73
  export {
56
74
  createHonoServer
@@ -1,12 +1,14 @@
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 } from '../hono-server-options-base.d-DChVrA1u.mjs';
4
+ import { a as WithoutWebsocket, H as HonoServerOptionsBase } from '../hono-server-options-base.d-XkJeTOq3.js';
5
5
  import 'hono/hono-base';
6
+ import 'hono/ws';
6
7
  import 'react-router';
7
8
 
8
- interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {
9
+ interface HonoCloudflareOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
9
10
  }
11
+ type HonoServerOptions<E extends Env = BlankEnv> = HonoCloudflareOptions<E> & Omit<WithoutWebsocket<E>, "useWebSocket">;
10
12
  /**
11
13
  * Create a Hono server
12
14
  *
@@ -1,23 +1,29 @@
1
+ import {
2
+ cache
3
+ } from "../chunk-V3H4JZ4H.js";
4
+
1
5
  // src/adapters/cloudflare.ts
2
6
  import { Hono } from "hono";
3
7
  import { createMiddleware } from "hono/factory";
4
8
  import { logger } from "hono/logger";
5
9
  import { createRequestHandler } from "react-router";
6
- async function createHonoServer(options = {}) {
10
+ async function createHonoServer(options) {
7
11
  const mergedOptions = {
8
12
  ...options,
9
- defaultLogger: options.defaultLogger ?? true
13
+ defaultLogger: options?.defaultLogger ?? true
10
14
  };
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());
15
+ const mode = import.meta.env.MODE || "production";
16
+ const DEV = mode === "development";
17
+ const app = new Hono(mergedOptions.honoOptions || mergedOptions.app);
18
+ if (DEV) {
19
+ const { serveStatic } = await import("@hono/node-server/serve-static");
20
+ app.use("*", cache(60 * 60), serveStatic({ root: "./public" }));
16
21
  }
17
- if (mergedOptions.configure) {
18
- await mergedOptions.configure(server);
22
+ if (mergedOptions.defaultLogger) {
23
+ app.use("*", logger());
19
24
  }
20
- server.use(async (c, next) => {
25
+ await mergedOptions.configure?.(app);
26
+ app.use(async (c, next) => {
21
27
  const build = await import(
22
28
  // @ts-expect-error - Virtual module provided by React Router at build time
23
29
  "virtual:react-router/server-build"
@@ -28,10 +34,10 @@ async function createHonoServer(options = {}) {
28
34
  return requestHandler(c2.req.raw, loadContext instanceof Promise ? await loadContext : loadContext);
29
35
  })(c, next);
30
36
  });
31
- if (!PRODUCTION) {
37
+ if (DEV) {
32
38
  console.log("\u{1F6A7} Running in development mode");
33
39
  }
34
- return server;
40
+ return app;
35
41
  }
36
42
  export {
37
43
  createHonoServer
@@ -1,12 +1,13 @@
1
- import * as hono_types from 'hono/types';
2
- import { BlankEnv } from 'hono/types';
3
1
  import { AddressInfo } from 'node:net';
2
+ import { ServerType } from '@hono/node-server';
4
3
  import { Env, Hono } from 'hono';
5
- import { H as HonoServerOptionsBase } from '../hono-server-options-base.d-DChVrA1u.mjs';
4
+ import { BlankEnv } from 'hono/types';
5
+ import { W as WithWebsocket, a as WithoutWebsocket, H as HonoServerOptionsBase } from '../hono-server-options-base.d-XkJeTOq3.js';
6
6
  import { ServerOptions, createServer } from 'node:http';
7
7
  import { ServerOptions as ServerOptions$2, createServer as createServer$2, SecureServerOptions, createSecureServer } from 'node:http2';
8
8
  import { ServerOptions as ServerOptions$1, createServer as createServer$1 } from 'node:https';
9
9
  import 'hono/hono-base';
10
+ import 'hono/ws';
10
11
  import 'react-router';
11
12
 
12
13
  type createHttpOptions = {
@@ -31,7 +32,7 @@ type CreateNodeServerOptions =
31
32
  | createHttp2Options
32
33
  | createSecureHttp2Options;
33
34
 
34
- interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
35
+ interface HonoNodeServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
35
36
  /**
36
37
  * Listening listener (production mode only)
37
38
  *
@@ -46,12 +47,20 @@ interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsB
46
47
  * {@link https://hono.dev/docs/getting-started/nodejs#http2}
47
48
  */
48
49
  customNodeServer?: CreateNodeServerOptions;
50
+ /**
51
+ * Callback executed just after `serve` from `@hono/node-server`
52
+ */
53
+ onServe?: (server: ServerType) => void;
49
54
  }
55
+ type HonoServerOptionsWithWebSocket<E extends Env = BlankEnv> = HonoNodeServerOptions<E> & WithWebsocket<E>;
56
+ type HonoServerOptionsWithoutWebSocket<E extends Env = BlankEnv> = HonoNodeServerOptions<E> & WithoutWebsocket<E>;
57
+ type HonoServerOptions<E extends Env = BlankEnv> = HonoServerOptionsWithWebSocket<E> | HonoServerOptionsWithoutWebSocket<E>;
50
58
  /**
51
59
  * Create a Hono server
52
60
  *
53
61
  * @param config {@link HonoServerOptions} - The configuration options for the server
54
62
  */
55
- declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptions<E>): Promise<Hono<E, hono_types.BlankSchema, "/">>;
63
+ declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptionsWithoutWebSocket<E>): Promise<Hono<E>>;
64
+ declare function createHonoServer<E extends Env = BlankEnv>(options?: HonoServerOptionsWithWebSocket<E>): Promise<Hono<E>>;
56
65
 
57
66
  export { type HonoServerOptions, createHonoServer };
@@ -1,6 +1,11 @@
1
+ import {
2
+ cleanUpgradeListeners,
3
+ createWebSocket,
4
+ patchUpgradeListener
5
+ } from "../chunk-27A6I7NN.js";
1
6
  import {
2
7
  cache
3
- } from "../chunk-ENK5WJB4.mjs";
8
+ } from "../chunk-V3H4JZ4H.js";
4
9
 
5
10
  // src/adapters/node.ts
6
11
  import { serve } from "@hono/node-server";
@@ -9,34 +14,40 @@ import { Hono } from "hono";
9
14
  import { createMiddleware } from "hono/factory";
10
15
  import { logger } from "hono/logger";
11
16
  import { createRequestHandler } from "react-router";
12
- async function createHonoServer(options = {}) {
17
+ async function createHonoServer(options) {
13
18
  const mergedOptions = {
19
+ ...options,
14
20
  listeningListener: (info) => {
15
21
  console.log(`\u{1F680} Server started on port ${info.port}`);
16
22
  console.log(`\u{1F30D} http://127.0.0.1:${info.port}`);
17
23
  },
18
- ...options,
19
- port: options.port || Number(process.env.PORT) || 3e3,
20
- defaultLogger: options.defaultLogger ?? true
24
+ port: options?.port || Number(process.env.PORT) || 3e3,
25
+ defaultLogger: options?.defaultLogger ?? true
21
26
  };
22
- const mode = import.meta.env.MODE;
27
+ const mode = import.meta.env.MODE || "production";
23
28
  const PRODUCTION = mode === "production";
24
- const server = new Hono(mergedOptions.honoOptions);
29
+ const app = new Hono(mergedOptions.honoOptions || mergedOptions.app);
25
30
  const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
26
- server.use(
31
+ const { upgradeWebSocket, injectWebSocket } = await createWebSocket({
32
+ app,
33
+ enabled: mergedOptions.useWebSocket ?? false
34
+ });
35
+ app.use(
27
36
  `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
28
37
  cache(60 * 60 * 24 * 365),
29
38
  // 1 year
30
39
  serveStatic({ root: clientBuildPath })
31
40
  );
32
- server.use("*", cache(60 * 60), serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" }));
41
+ app.use("*", cache(60 * 60), serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" }));
33
42
  if (mergedOptions.defaultLogger) {
34
- server.use("*", logger());
43
+ app.use("*", logger());
35
44
  }
36
- if (mergedOptions.configure) {
37
- await mergedOptions.configure(server);
45
+ if (mergedOptions.useWebSocket) {
46
+ await mergedOptions.configure(app, { upgradeWebSocket });
47
+ } else {
48
+ await mergedOptions.configure?.(app);
38
49
  }
39
- server.use(async (c, next) => {
50
+ app.use(async (c, next) => {
40
51
  const build = await import(
41
52
  // @ts-expect-error - Virtual module provided by React Router at build time
42
53
  "virtual:react-router/server-build"
@@ -48,18 +59,25 @@ async function createHonoServer(options = {}) {
48
59
  })(c, next);
49
60
  });
50
61
  if (PRODUCTION) {
51
- serve(
62
+ const server = serve(
52
63
  {
53
- ...server,
64
+ ...app,
54
65
  ...mergedOptions.customNodeServer,
55
66
  port: mergedOptions.port
56
67
  },
57
68
  mergedOptions.listeningListener
58
69
  );
59
- } else {
70
+ mergedOptions.onServe?.(server);
71
+ injectWebSocket(server);
72
+ } else if (globalThis.__viteDevServer?.httpServer) {
73
+ const httpServer = globalThis.__viteDevServer.httpServer;
74
+ cleanUpgradeListeners(httpServer);
75
+ mergedOptions.onServe?.(httpServer);
76
+ injectWebSocket(httpServer);
77
+ patchUpgradeListener(httpServer);
60
78
  console.log("\u{1F6A7} Dev server started");
61
79
  }
62
- return server;
80
+ return app;
63
81
  }
64
82
  export {
65
83
  createHonoServer
@@ -0,0 +1,71 @@
1
+ // src/helpers.ts
2
+ var defaultWebSocket = {
3
+ upgradeWebSocket: () => async () => {
4
+ },
5
+ injectWebSocket: (server) => server
6
+ };
7
+ async function createWebSocket({ app, enabled }) {
8
+ if (!enabled) {
9
+ return defaultWebSocket;
10
+ }
11
+ const mode = import.meta.env.MODE;
12
+ const DEV = mode === "development";
13
+ const runtime = import.meta.env.REACT_ROUTER_HONO_SERVER_RUNTIME;
14
+ if (DEV || runtime === "node") {
15
+ const { createNodeWebSocket } = await import("@hono/node-ws");
16
+ const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
17
+ return {
18
+ upgradeWebSocket,
19
+ injectWebSocket(server) {
20
+ injectWebSocket(server);
21
+ return server;
22
+ }
23
+ };
24
+ }
25
+ if (runtime === "bun") {
26
+ const { createBunWebSocket } = await import("hono/bun");
27
+ const { upgradeWebSocket, websocket } = createBunWebSocket();
28
+ return {
29
+ upgradeWebSocket,
30
+ injectWebSocket: (server) => {
31
+ return {
32
+ ...server,
33
+ websocket
34
+ };
35
+ }
36
+ };
37
+ }
38
+ return defaultWebSocket;
39
+ }
40
+ function cleanUpgradeListeners(httpServer) {
41
+ const upgradeListeners = httpServer.listeners("upgrade").filter((listener) => listener.name !== "hmrServerWsListener");
42
+ for (const listener of upgradeListeners) {
43
+ httpServer.removeListener(
44
+ "upgrade",
45
+ /* @ts-ignore - we don't care */
46
+ listener
47
+ );
48
+ }
49
+ }
50
+ function patchUpgradeListener(httpServer) {
51
+ const upgradeListeners = httpServer.listeners("upgrade").filter((listener) => listener.name !== "hmrServerWsListener");
52
+ for (const listener of upgradeListeners) {
53
+ httpServer.removeListener(
54
+ "upgrade",
55
+ /* @ts-ignore - we don't care */
56
+ listener
57
+ );
58
+ httpServer.on("upgrade", (request, ...rest) => {
59
+ if (request.headers["sec-websocket-protocol"] === "vite-hmr") {
60
+ return;
61
+ }
62
+ return listener(request, ...rest);
63
+ });
64
+ }
65
+ }
66
+
67
+ export {
68
+ createWebSocket,
69
+ cleanUpgradeListeners,
70
+ patchUpgradeListener
71
+ };
@@ -2,6 +2,7 @@ import { DevServerOptions } from '@hono/vite-dev-server';
2
2
  import { Plugin } from 'vite';
3
3
 
4
4
  type Runtime = "node" | "bun" | "cloudflare";
5
+
5
6
  type ReactRouterHonoServerPluginOptions = {
6
7
  /**
7
8
  * The runtime to use for the server.
@@ -16,7 +17,7 @@ type ReactRouterHonoServerPluginOptions = {
16
17
  *
17
18
  * Defaults to `${appDirectory}/server[.ts | /index.ts]` if present.
18
19
  *
19
- * Fallback to a virtual module `virtual:react-router-hono-server/server`.
20
+ * Fallback to a virtual module `virtual:react-router-hono-server/server`.`
20
21
  */
21
22
  serverEntryPoint?: string;
22
23
  /**
@@ -33,18 +33,18 @@ function reactRouterHonoServer(options = {}) {
33
33
  return;
34
34
  }
35
35
  if (runtime === "cloudflare" && !config.plugins?.find((p) => p && "name" in p && p.name === "react-router-cloudflare-vite-dev-proxy")) {
36
- console.error(
36
+ console.warn(
37
37
  `\x1B[31mMissing cloudflareDevProxy() in your vite.config.ts.
38
38
  Please add it to your plugins: import { cloudflareDevProxy } from "@react-router/dev/vite/cloudflare";\x1B[0m
39
39
  `
40
40
  );
41
- throw new Error("Missing mandatory plugin cloudflareDevProxy() in vite.config.ts");
42
41
  }
43
42
  const baseConfig = {
44
43
  // Define environment variables that are hot-swapped during development and SSR build
45
44
  define: {
46
45
  "import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY": JSON.stringify(pluginConfig.buildDirectory),
47
- "import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR": JSON.stringify(pluginConfig.assetsDir)
46
+ "import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR": JSON.stringify(pluginConfig.assetsDir),
47
+ "import.meta.env.REACT_ROUTER_HONO_SERVER_RUNTIME": JSON.stringify(runtime)
48
48
  },
49
49
  ssr: {
50
50
  target: runtime === "cloudflare" ? "webworker" : void 0,
@@ -66,7 +66,8 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
66
66
  }
67
67
  };
68
68
  },
69
- configureServer(server) {
69
+ async configureServer(server) {
70
+ globalThis.__viteDevServer = server;
70
71
  if (!pluginConfig) {
71
72
  return;
72
73
  }
@@ -0,0 +1,86 @@
1
+ import { Env, Hono, Context } from 'hono';
2
+ import { HonoOptions } from 'hono/hono-base';
3
+ import { UpgradeWebSocket } from 'hono/ws';
4
+ import { ServerBuild, AppLoadContext } from 'react-router';
5
+
6
+ interface HonoServerOptionsBase<E extends Env> {
7
+ /**
8
+ * Hono app to use
9
+ *
10
+ * {@link Hono}
11
+ */
12
+ app?: Hono<E>;
13
+ /**
14
+ * Enable the default logger
15
+ *
16
+ * Defaults to `true`
17
+ */
18
+ defaultLogger?: boolean;
19
+ /**
20
+ * The port to start the server on
21
+ *
22
+ * Defaults to `process.env.PORT || 3000`
23
+ */
24
+ port?: number;
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
+ * @deprecated Use `app` instead
48
+ */
49
+ honoOptions?: HonoOptions<E>;
50
+ }
51
+
52
+ interface WithWebsocket<E extends Env> {
53
+ /**
54
+ * Enable WebSockets support in `configure`
55
+ *
56
+ * For `bun` and `cloudflare` we will use the `@hono/node-ws`'s `injectWebSocket` on dev (only),
57
+ *
58
+ * Defaults to `false`
59
+ */
60
+ useWebSocket: true;
61
+ /**
62
+ * Customize the Hono server, for example, adding middleware
63
+ *
64
+ * It is applied after the default middleware and before the React Router middleware
65
+ */
66
+ configure: (app: Hono<E>, options: { upgradeWebSocket: UpgradeWebSocket }) => Promise<void> | void;
67
+ }
68
+
69
+ interface WithoutWebsocket<E extends Env> {
70
+ /**
71
+ * Enable WebSockets support in `configure`
72
+ *
73
+ * For `bun` and `cloudflare` we will use the `@hono/node-ws`'s `injectWebSocket` on dev (only),
74
+ *
75
+ * Defaults to `false`
76
+ */
77
+ useWebSocket?: false | undefined;
78
+ /**
79
+ * Customize the Hono server, for example, adding middleware
80
+ *
81
+ * It is applied after the default middleware and before the React Router middleware
82
+ */
83
+ configure?: (app: Hono<E>) => Promise<void> | void;
84
+ }
85
+
86
+ export type { HonoServerOptionsBase as H, WithWebsocket as W, WithoutWebsocket as a };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  cache
3
- } from "./chunk-ENK5WJB4.mjs";
3
+ } from "./chunk-V3H4JZ4H.js";
4
4
  export {
5
5
  cache
6
6
  };
package/package.json CHANGED
@@ -1,41 +1,42 @@
1
1
  {
2
2
  "name": "react-router-hono-server",
3
- "version": "2.1.2",
3
+ "version": "2.2.0",
4
+ "type": "module",
4
5
  "description": "The Vite plugin you need to create a Hono server for your React Router app in less than 10 seconds.",
5
6
  "exports": {
6
7
  "./node": {
7
8
  "import": {
8
- "import": "./dist/adapters/node.mjs",
9
- "types": "./dist/adapters/node.d.mts",
10
- "default": "./dist/adapters/node.mjs"
9
+ "import": "./dist/adapters/node.js",
10
+ "types": "./dist/adapters/node.d.ts",
11
+ "default": "./dist/adapters/node.js"
11
12
  }
12
13
  },
13
14
  "./bun": {
14
15
  "import": {
15
- "import": "./dist/adapters/bun.mjs",
16
- "types": "./dist/adapters/bun.d.mts",
17
- "default": "./dist/adapters/bun.mjs"
16
+ "import": "./dist/adapters/bun.js",
17
+ "types": "./dist/adapters/bun.d.ts",
18
+ "default": "./dist/adapters/bun.js"
18
19
  }
19
20
  },
20
21
  "./cloudflare": {
21
22
  "import": {
22
- "import": "./dist/adapters/cloudflare.mjs",
23
- "types": "./dist/adapters/cloudflare.d.mts",
24
- "default": "./dist/adapters/cloudflare.mjs"
23
+ "import": "./dist/adapters/cloudflare.js",
24
+ "types": "./dist/adapters/cloudflare.d.ts",
25
+ "default": "./dist/adapters/cloudflare.js"
25
26
  }
26
27
  },
27
28
  "./dev": {
28
29
  "import": {
29
- "import": "./dist/dev.mjs",
30
- "types": "./dist/dev.d.mts",
31
- "default": "./dist/dev.mjs"
30
+ "import": "./dist/dev.js",
31
+ "types": "./dist/dev.d.ts",
32
+ "default": "./dist/dev.js"
32
33
  }
33
34
  },
34
35
  "./middlewares": {
35
36
  "import": {
36
- "import": "./dist/middlewares.mjs",
37
- "types": "./dist/middlewares.d.mts",
38
- "default": "./dist/middlewares.mjs"
37
+ "import": "./dist/middlewares.js",
38
+ "types": "./dist/middlewares.d.ts",
39
+ "default": "./dist/middlewares.js"
39
40
  }
40
41
  }
41
42
  },
@@ -62,19 +63,20 @@
62
63
  "url": "https://github.com/rphlmr/react-router-hono-server/issues"
63
64
  },
64
65
  "bin": {
65
- "react-router-hono-server": "dist/cli.mjs"
66
+ "react-router-hono-server": "dist/cli.js"
66
67
  },
67
68
  "files": ["dist"],
68
- "workspaces": [".", "examples/*"],
69
+ "workspaces": [".", "examples/**/*"],
69
70
  "homepage": "https://github.com/rphlmr/react-router-hono-server#readme",
70
71
  "dependencies": {
71
72
  "@drizzle-team/brocli": "^0.11.0",
72
73
  "@hono/node-server": "^1.13.7",
74
+ "@hono/node-ws": "^1.0.4",
73
75
  "@hono/vite-dev-server": "^0.17.0",
74
76
  "hono": "^4.6.11"
75
77
  },
76
78
  "optionalDependencies": {
77
- "miniflare": "^3.20241106.1",
79
+ "miniflare": "^3.20241205.0",
78
80
  "wrangler": "^3.91.0"
79
81
  },
80
82
  "devDependencies": {
@@ -1,107 +0,0 @@
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 };
@@ -1,54 +0,0 @@
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 };
File without changes
File without changes
File without changes