react-router-hono-server 2.4.0 → 2.6.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
@@ -254,6 +254,22 @@ main = "./build/server/index.js"
254
254
  assets = { directory = "./build/client/" }
255
255
  ```
256
256
 
257
+ ##### Custom assets serving
258
+ You can set Cloudflare `experimental_serve_directly` and delegate assets serving to Hono, like for Node and Bun.
259
+
260
+ > [!TIP]
261
+ > Check https://developers.cloudflare.com/workers/static-assets/binding/#experimental_serve_directly
262
+
263
+ > [!TIP]
264
+ > Check this [example](./examples/cloudflare/simple/) to see how to use it.
265
+
266
+ ```toml
267
+ [assets]
268
+ directory = "./build/client/"
269
+ binding = "ASSETS"
270
+ experimental_serve_directly = false
271
+ ```
272
+
257
273
  ## How it works
258
274
 
259
275
  This helper works differently depending on the environment.
@@ -313,8 +329,11 @@ type ReactRouterHonoServerPluginOptions = {
313
329
  ##### All adapters
314
330
  ```ts
315
331
  export type HonoServerOptions<E extends Env = BlankEnv> = {
316
- /**
317
- * Hono app to use
332
+ /**
333
+ * The base Hono app to use
334
+ *
335
+ * It will be used to mount the React Router server on the `basename` path
336
+ * defined in the [React Router config](https://api.reactrouter.com/v7/types/_react_router_dev.config.Config.html)
318
337
  *
319
338
  * {@link Hono}
320
339
  */
@@ -359,13 +378,11 @@ export type HonoServerOptions<E extends Env = BlankEnv> = {
359
378
  }
360
379
  ) => Promise<AppLoadContext> | AppLoadContext;
361
380
  /**
362
- * Listening listener (production mode only)
381
+ * Hook to add middleware that runs before any built-in middleware, including assets serving.
363
382
  *
364
- * It is called when the server is listening
365
- *
366
- * Defaults log the port
383
+ * You can use it to add protection middleware, for example.
367
384
  */
368
- listeningListener?: (info: AddressInfo) => void;
385
+ beforeAll?: (app: Hono<E>) => Promise<void> | void;
369
386
  };
370
387
  ```
371
388
 
@@ -417,6 +434,19 @@ export async function loader({ context }: Route.LoaderArgs) {
417
434
  }
418
435
  ```
419
436
 
437
+ > [!TIP]
438
+ > If you declare your `getLoadContext` function in a separate file, you can use the helper `createGetLoadContext` from `react-router-hono-server/{adapter}`
439
+ > ```ts
440
+ > import { createGetLoadContext } from "react-router-hono-server/node";
441
+ >
442
+ > export const getLoadContext = createGetLoadContext((c, { mode, build }) => {
443
+ > const isProductionMode = mode === "production";
444
+ > return {
445
+ > appVersion: isProductionMode ? build.assets.version : "dev",
446
+ > };
447
+ > });
448
+ > ```
449
+
420
450
  ##### Node
421
451
  ```ts
422
452
  export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
@@ -442,6 +472,18 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
442
472
  * For example, you can use this to bind `@hono/node-ws`'s `injectWebSocket`
443
473
  */
444
474
  onServe?: (server: ServerType) => void;
475
+ /**
476
+ * The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance.
477
+ *
478
+ * If you want this behavior, set it to `true`
479
+ *
480
+ * 🚨 Setting this to `true` can break `request.clone()` if you later check `instanceof Request`.
481
+ *
482
+ * {@link https://github.com/honojs/node-server?tab=readme-ov-file#overrideglobalobjects}
483
+ *
484
+ * @default false
485
+ */
486
+ overrideGlobalObjects?: boolean;
445
487
  }
446
488
  ```
447
489
 
@@ -464,6 +506,18 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoSe
464
506
 
465
507
  ## Middleware
466
508
 
509
+ 🚨 Redirecting from a middleware
510
+ > [!IMPORTANT]
511
+ > You **have to** use the `reactRouterRedirect` helper to redirect from a middleware.
512
+ >
513
+ > It returns a single-fetch-like response.
514
+ >
515
+ > If you use `c.redirect`, it will not work as expected and you will get a `Unable to decode turbo-stream response` error.
516
+ >
517
+ >```ts
518
+ > import { reactRouterRedirect } from "react-router-hono-server/http";
519
+ >```
520
+
467
521
  Middleware are functions that are called before React Router calls your loader/action.
468
522
 
469
523
  Hono is the perfect tool for this, as it supports middleware out of the box.
@@ -477,6 +531,31 @@ See how [Shelf.nu](https://github.com/Shelf-nu/shelf.nu/blob/main/server/middlew
477
531
  > [!TIP]
478
532
  > This lib exports one middleware `cache` (`react-router-hono-server/middleware`) that you can use to cache your responses.
479
533
 
534
+ ### `beforeAll`
535
+ You can use the `beforeAll` option to add middleware that runs before any built-in middleware, including assets serving.
536
+
537
+ You can use it to add protection middleware, for example.
538
+
539
+ > [!TIP]
540
+ > When you check the path to protect, don't forget to use `c.req.path.includes("")` to handle `.data` requests (`loader`)!
541
+
542
+ ```ts
543
+ import { reactRouterRedirect } from "react-router-hono-server/http";
544
+ import { createHonoServer } from "react-router-hono-server/node";
545
+
546
+ export default await createHonoServer({
547
+ beforeAll(app) {
548
+ app.use(async (c, next) => {
549
+ if (c.req.path.includes("/protected") && !c.req.header("Authorization")) {
550
+ return reactRouterRedirect("/login");
551
+ }
552
+
553
+ return next();
554
+ });
555
+ },
556
+ });
557
+ ```
558
+
480
559
  ### Using remix-hono middleware
481
560
 
482
561
  It is easy to use [remix-hono](https://github.com/sergiodxa/remix-hono) middleware with this package.
@@ -645,6 +724,55 @@ Cloudflare requires a different approach to WebSockets, based on Durable Objects
645
724
  >
646
725
  > Work in progress on Cloudflare team: https://github.com/flarelabs-net/vite-plugin-cloudflare
647
726
 
727
+ ## Basename and Hono sub apps
728
+
729
+ > [!NOTE]
730
+ > By default, the React Router app is mounted at `/` (default `basename` value).
731
+ >
732
+ > You may not need to use this option. It's for advanced use cases.
733
+
734
+ > [!TIP]
735
+ > Check this [example](./examples/node/custom-mount/) to see how to use it.
736
+
737
+ You can use the `basename` option in your React Router config (`react-router.config.ts`) to mount your React Router app on a subpath.
738
+
739
+ It will automatically mount the app on the subpath.
740
+
741
+ ```ts
742
+ // react-router.config.ts
743
+ import type { Config } from "@react-router/dev/config";
744
+
745
+ export default {
746
+ basename: "/app", // Now the React Router app will be mounted on /app
747
+ } satisfies Config;
748
+ ```
749
+
750
+ Then, you can use the `app` option in `createHonoServer` to pass your "root" Hono app. This will be used to mount the React Router app on the `basename` path.
751
+
752
+ ```ts
753
+ import { Hono } from "hono";
754
+ import { createHonoServer } from "react-router-hono-server/node";
755
+ import { API_BASENAME, api } from "./api";
756
+ import { getLoadContext } from "./context";
757
+
758
+ // Create a root Hono app
759
+ const app = new Hono();
760
+
761
+ // Mount the API app at /api
762
+ app.route(API_BASENAME, api);
763
+
764
+ export default await createHonoServer({
765
+ // Pass the root Hono app to the server.
766
+ // It will be used to mount the React Router app on the `basename` defined in react-router.config.ts
767
+ app,
768
+ getLoadContext,
769
+ });
770
+ ```
771
+ > [!NOTE]
772
+ > You now have two entry points!
773
+ > - `/api` - for your API
774
+ > - `/app` - for your React Router app
775
+
648
776
  ## Pre-rendering
649
777
  You should be able to use pre-rendering with this package.
650
778
 
@@ -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 { 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';
4
+ import { W as WithWebsocket, a as WithoutWebsocket, H as HonoServerOptionsBase } from '../helpers-F2RS9Syt.js';
5
+ export { c as createGetLoadContext } from '../helpers-F2RS9Syt.js';
7
6
  import 'react-router';
7
+ import 'hono/ws';
8
8
 
9
9
  type CustomBunServer = Serve & ServeOptions & {
10
10
  websocket?: unknown;
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  bindIncomingRequestSocketInfo,
3
3
  cleanUpgradeListeners,
4
+ createGetLoadContext,
4
5
  createWebSocket,
6
+ importBuild,
5
7
  patchUpgradeListener
6
- } from "../chunk-D4WESSFB.js";
8
+ } from "../chunk-DZZCDCBI.js";
7
9
  import {
8
10
  cache
9
11
  } from "../chunk-V3H4JZ4H.js";
@@ -15,6 +17,7 @@ import { createMiddleware } from "hono/factory";
15
17
  import { logger } from "hono/logger";
16
18
  import { createRequestHandler } from "react-router";
17
19
  async function createHonoServer(options) {
20
+ const basename = import.meta.env.REACT_ROUTER_HONO_SERVER_BASENAME;
18
21
  const mergedOptions = {
19
22
  ...options,
20
23
  port: options?.port || Number(options?.customBunServer?.port) || Number(process.env.PORT) || 3e3,
@@ -22,8 +25,8 @@ async function createHonoServer(options) {
22
25
  };
23
26
  const mode = import.meta.env.MODE || "production";
24
27
  const PRODUCTION = mode === "production";
25
- const app = new Hono(mergedOptions.honoOptions || mergedOptions.app);
26
28
  const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
29
+ const app = new Hono(mergedOptions.app);
27
30
  const { upgradeWebSocket, injectWebSocket } = await createWebSocket({
28
31
  app,
29
32
  enabled: mergedOptions.useWebSocket ?? false
@@ -31,13 +34,19 @@ async function createHonoServer(options) {
31
34
  if (!PRODUCTION) {
32
35
  app.use(bindIncomingRequestSocketInfo());
33
36
  }
37
+ await mergedOptions.beforeAll?.(app);
34
38
  app.use(
35
39
  `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
36
40
  cache(60 * 60 * 24 * 365),
37
41
  // 1 year
38
42
  serveStatic({ root: clientBuildPath })
39
43
  );
40
- app.use("*", cache(60 * 60), serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" }));
44
+ app.use(
45
+ "*",
46
+ cache(60 * 60),
47
+ // 1 hour
48
+ serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" })
49
+ );
41
50
  if (mergedOptions.defaultLogger) {
42
51
  app.use("*", logger());
43
52
  }
@@ -46,17 +55,21 @@ async function createHonoServer(options) {
46
55
  } else {
47
56
  await mergedOptions.configure?.(app);
48
57
  }
49
- app.use(async (c, next) => {
50
- const build = await import(
51
- // @ts-expect-error - Virtual module provided by React Router at build time
52
- "virtual:react-router/server-build"
53
- );
58
+ const reactRouterApp = new Hono({
59
+ strict: false
60
+ });
61
+ reactRouterApp.use(async (c, next) => {
62
+ const build = await importBuild();
54
63
  return createMiddleware(async (c2) => {
55
64
  const requestHandler = createRequestHandler(build, mode);
56
65
  const loadContext = mergedOptions.getLoadContext?.(c2, { build, mode });
57
66
  return requestHandler(c2.req.raw, loadContext instanceof Promise ? await loadContext : loadContext);
58
67
  })(c, next);
59
68
  });
69
+ app.route(`${basename}`, reactRouterApp);
70
+ if (basename) {
71
+ app.route(`${basename}.data`, reactRouterApp);
72
+ }
60
73
  let server = {
61
74
  ...mergedOptions.customBunServer,
62
75
  fetch: app.fetch,
@@ -75,5 +88,6 @@ async function createHonoServer(options) {
75
88
  return server;
76
89
  }
77
90
  export {
91
+ createGetLoadContext,
78
92
  createHonoServer
79
93
  };
@@ -1,12 +1,12 @@
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 { a as WithoutWebsocket, H as HonoServerOptionsBase } from '../hono-server-options-base.d-XkJeTOq3.js';
5
- import 'hono/hono-base';
6
- import 'hono/ws';
4
+ import { a as WithoutWebsocket, H as HonoServerOptionsBase } from '../helpers-F2RS9Syt.js';
5
+ export { c as createGetLoadContext } from '../helpers-F2RS9Syt.js';
7
6
  import 'react-router';
7
+ import 'hono/ws';
8
8
 
9
- interface HonoCloudflareOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
9
+ interface HonoCloudflareOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {
10
10
  }
11
11
  type HonoServerOptions<E extends Env = BlankEnv> = HonoCloudflareOptions<E> & Omit<WithoutWebsocket<E>, "useWebSocket">;
12
12
  /**
@@ -1,6 +1,8 @@
1
1
  import {
2
- bindIncomingRequestSocketInfo
3
- } from "../chunk-D4WESSFB.js";
2
+ bindIncomingRequestSocketInfo,
3
+ createGetLoadContext,
4
+ importBuild
5
+ } from "../chunk-DZZCDCBI.js";
4
6
  import {
5
7
  cache
6
8
  } from "../chunk-V3H4JZ4H.js";
@@ -11,38 +13,93 @@ import { createMiddleware } from "hono/factory";
11
13
  import { logger } from "hono/logger";
12
14
  import { createRequestHandler } from "react-router";
13
15
  async function createHonoServer(options) {
16
+ const basename = import.meta.env.REACT_ROUTER_HONO_SERVER_BASENAME;
14
17
  const mergedOptions = {
15
18
  ...options,
16
19
  defaultLogger: options?.defaultLogger ?? true
17
20
  };
18
21
  const mode = import.meta.env.MODE || "production";
19
- const DEV = mode === "development";
20
- const app = new Hono(mergedOptions.honoOptions || mergedOptions.app);
21
- if (DEV) {
22
+ const PRODUCTION = mode === "production";
23
+ const app = new Hono(mergedOptions.app);
24
+ await mergedOptions.beforeAll?.(app);
25
+ app.use(
26
+ // https://developers.cloudflare.com/workers/static-assets/binding/#experimental_serve_directly
27
+ `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
28
+ cache(60 * 60 * 24 * 365),
29
+ // 1 year
30
+ serveCloudflareAssets()
31
+ );
32
+ if (PRODUCTION) {
33
+ app.use(
34
+ // https://developers.cloudflare.com/workers/static-assets/binding/#experimental_serve_directly
35
+ "*",
36
+ cache(60 * 60),
37
+ // 1 hour
38
+ serveCloudflareAssets()
39
+ );
40
+ } else {
22
41
  const { serveStatic } = await import("@hono/node-server/serve-static");
23
- app.use("*", cache(60 * 60), serveStatic({ root: "./public" }));
42
+ app.use(
43
+ "*",
44
+ cache(60 * 60),
45
+ // 1 hour
46
+ serveStatic({ root: "./public" })
47
+ );
24
48
  app.use(bindIncomingRequestSocketInfo());
25
49
  }
26
50
  if (mergedOptions.defaultLogger) {
27
51
  app.use("*", logger());
28
52
  }
29
53
  await mergedOptions.configure?.(app);
30
- app.use(async (c, next) => {
31
- const build = await import(
32
- // @ts-expect-error - Virtual module provided by React Router at build time
33
- "virtual:react-router/server-build"
34
- );
54
+ const reactRouterApp = new Hono({
55
+ strict: false
56
+ });
57
+ reactRouterApp.use(async (c, next) => {
58
+ const build = await importBuild();
35
59
  return createMiddleware(async (c2) => {
36
60
  const requestHandler = createRequestHandler(build, mode);
37
61
  const loadContext = mergedOptions.getLoadContext?.(c2, { build, mode });
38
62
  return requestHandler(c2.req.raw, loadContext instanceof Promise ? await loadContext : loadContext);
39
63
  })(c, next);
40
64
  });
41
- if (DEV) {
65
+ app.route(`${basename}`, reactRouterApp);
66
+ if (basename) {
67
+ app.route(`${basename}.data`, reactRouterApp);
68
+ }
69
+ if (!PRODUCTION) {
42
70
  console.log("\u{1F6A7} Running in development mode");
43
71
  }
44
72
  return app;
45
73
  }
74
+ var warned = false;
75
+ function serveCloudflareAssets() {
76
+ return createMiddleware(async (c, next) => {
77
+ const binding = c.env?.ASSETS;
78
+ if (!binding) {
79
+ if (!warned) {
80
+ console.info(
81
+ "\x1B[33m\nThe binding ASSETS is not set. Falling back to Cloudflare serving.\nhttps://developers.cloudflare.com/workers/static-assets/binding/#binding\n\x1B[0m"
82
+ );
83
+ }
84
+ warned = true;
85
+ return next();
86
+ }
87
+ try {
88
+ let response = await binding.fetch(
89
+ c.req.url,
90
+ c.req.raw.clone()
91
+ );
92
+ if (response.status >= 400) {
93
+ return next();
94
+ }
95
+ response = new Response(response.body, response);
96
+ return response;
97
+ } catch {
98
+ return next();
99
+ }
100
+ });
101
+ }
46
102
  export {
103
+ createGetLoadContext,
47
104
  createHonoServer
48
105
  };
@@ -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 { W as WithWebsocket, a as WithoutWebsocket, H as HonoServerOptionsBase } from '../hono-server-options-base.d-XkJeTOq3.js';
5
+ import { W as WithWebsocket, a as WithoutWebsocket, H as HonoServerOptionsBase } from '../helpers-F2RS9Syt.js';
6
+ export { c as createGetLoadContext } from '../helpers-F2RS9Syt.js';
6
7
  import { ServerOptions, createServer } from 'node:http';
7
8
  import { ServerOptions as ServerOptions$2, createServer as createServer$2, SecureServerOptions, createSecureServer } from 'node:http2';
8
9
  import { ServerOptions as ServerOptions$1, createServer as createServer$1 } from 'node:https';
9
- import 'hono/hono-base';
10
- import 'hono/ws';
11
10
  import 'react-router';
11
+ import 'hono/ws';
12
12
 
13
13
  type createHttpOptions = {
14
14
  serverOptions?: ServerOptions;
@@ -51,6 +51,18 @@ interface HonoNodeServerOptions<E extends Env = BlankEnv> extends HonoServerOpti
51
51
  * Callback executed just after `serve` from `@hono/node-server`
52
52
  */
53
53
  onServe?: (server: ServerType) => void;
54
+ /**
55
+ * The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance.
56
+ *
57
+ * If you this behavior, set it to `true`
58
+ *
59
+ * 🚨 Setting this to `true` can break `request.clone()` if you later check `instanceof Request`.
60
+ *
61
+ * {@link https://github.com/honojs/node-server?tab=readme-ov-file#overrideglobalobjects}
62
+ *
63
+ * @default false
64
+ */
65
+ overrideGlobalObjects?: boolean;
54
66
  }
55
67
  type HonoServerOptionsWithWebSocket<E extends Env = BlankEnv> = HonoNodeServerOptions<E> & WithWebsocket<E>;
56
68
  type HonoServerOptionsWithoutWebSocket<E extends Env = BlankEnv> = HonoNodeServerOptions<E> & WithoutWebsocket<E>;
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  bindIncomingRequestSocketInfo,
3
3
  cleanUpgradeListeners,
4
+ createGetLoadContext,
4
5
  createWebSocket,
6
+ importBuild,
5
7
  patchUpgradeListener
6
- } from "../chunk-D4WESSFB.js";
8
+ } from "../chunk-DZZCDCBI.js";
7
9
  import {
8
10
  cache
9
11
  } from "../chunk-V3H4JZ4H.js";
@@ -16,19 +18,24 @@ import { createMiddleware } from "hono/factory";
16
18
  import { logger } from "hono/logger";
17
19
  import { createRequestHandler } from "react-router";
18
20
  async function createHonoServer(options) {
21
+ const basename = import.meta.env.REACT_ROUTER_HONO_SERVER_BASENAME;
19
22
  const mergedOptions = {
20
23
  ...options,
21
24
  listeningListener: options?.listeningListener || ((info) => {
22
25
  console.log(`\u{1F680} Server started on port ${info.port}`);
23
26
  console.log(`\u{1F30D} http://127.0.0.1:${info.port}`);
27
+ if (basename !== "/") {
28
+ console.log(`\u{1F517} http://127.0.0.1:${info.port}${basename}`);
29
+ }
24
30
  }),
25
31
  port: options?.port || Number(process.env.PORT) || 3e3,
26
- defaultLogger: options?.defaultLogger ?? true
32
+ defaultLogger: options?.defaultLogger ?? true,
33
+ overrideGlobalObjects: options?.overrideGlobalObjects ?? false
27
34
  };
28
35
  const mode = import.meta.env.MODE || "production";
29
36
  const PRODUCTION = mode === "production";
30
- const app = new Hono(mergedOptions.honoOptions || mergedOptions.app);
31
37
  const clientBuildPath = `${import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY}/client`;
38
+ const app = new Hono(mergedOptions.app);
32
39
  const { upgradeWebSocket, injectWebSocket } = await createWebSocket({
33
40
  app,
34
41
  enabled: mergedOptions.useWebSocket ?? false
@@ -36,13 +43,19 @@ async function createHonoServer(options) {
36
43
  if (!PRODUCTION) {
37
44
  app.use(bindIncomingRequestSocketInfo());
38
45
  }
46
+ await mergedOptions.beforeAll?.(app);
39
47
  app.use(
40
48
  `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
41
49
  cache(60 * 60 * 24 * 365),
42
50
  // 1 year
43
51
  serveStatic({ root: clientBuildPath })
44
52
  );
45
- app.use("*", cache(60 * 60), serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" }));
53
+ app.use(
54
+ "*",
55
+ cache(60 * 60),
56
+ // 1 hour
57
+ serveStatic({ root: PRODUCTION ? clientBuildPath : "./public" })
58
+ );
46
59
  if (mergedOptions.defaultLogger) {
47
60
  app.use("*", logger());
48
61
  }
@@ -51,23 +64,28 @@ async function createHonoServer(options) {
51
64
  } else {
52
65
  await mergedOptions.configure?.(app);
53
66
  }
54
- app.use(async (c, next) => {
55
- const build = await import(
56
- // @ts-expect-error - Virtual module provided by React Router at build time
57
- "virtual:react-router/server-build"
58
- );
67
+ const reactRouterApp = new Hono({
68
+ strict: false
69
+ });
70
+ reactRouterApp.use(async (c, next) => {
71
+ const build = await importBuild();
59
72
  return createMiddleware(async (c2) => {
60
73
  const requestHandler = createRequestHandler(build, mode);
61
74
  const loadContext = mergedOptions.getLoadContext?.(c2, { build, mode });
62
75
  return requestHandler(c2.req.raw, loadContext instanceof Promise ? await loadContext : loadContext);
63
76
  })(c, next);
64
77
  });
78
+ app.route(`${basename}`, reactRouterApp);
79
+ if (basename) {
80
+ app.route(`${basename}.data`, reactRouterApp);
81
+ }
65
82
  if (PRODUCTION) {
66
83
  const server = serve(
67
84
  {
68
85
  ...app,
69
86
  ...mergedOptions.customNodeServer,
70
- port: mergedOptions.port
87
+ port: mergedOptions.port,
88
+ overrideGlobalObjects: mergedOptions.overrideGlobalObjects
71
89
  },
72
90
  mergedOptions.listeningListener
73
91
  );
@@ -84,5 +102,6 @@ async function createHonoServer(options) {
84
102
  return app;
85
103
  }
86
104
  export {
105
+ createGetLoadContext,
87
106
  createHonoServer
88
107
  };
@@ -78,10 +78,21 @@ function bindIncomingRequestSocketInfo() {
78
78
  return next();
79
79
  });
80
80
  }
81
+ async function importBuild() {
82
+ return import(
83
+ // @ts-expect-error - Virtual module provided by React Router at build time
84
+ "virtual:react-router/server-build"
85
+ );
86
+ }
87
+ function createGetLoadContext(getLoadContext) {
88
+ return getLoadContext;
89
+ }
81
90
 
82
91
  export {
83
92
  createWebSocket,
84
93
  cleanUpgradeListeners,
85
94
  patchUpgradeListener,
86
- bindIncomingRequestSocketInfo
95
+ bindIncomingRequestSocketInfo,
96
+ importBuild,
97
+ createGetLoadContext
87
98
  };
package/dist/dev.js CHANGED
@@ -45,7 +45,8 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
45
45
  define: {
46
46
  "import.meta.env.REACT_ROUTER_HONO_SERVER_BUILD_DIRECTORY": JSON.stringify(pluginConfig.buildDirectory),
47
47
  "import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR": JSON.stringify(pluginConfig.assetsDir),
48
- "import.meta.env.REACT_ROUTER_HONO_SERVER_RUNTIME": JSON.stringify(runtime)
48
+ "import.meta.env.REACT_ROUTER_HONO_SERVER_RUNTIME": JSON.stringify(runtime),
49
+ "import.meta.env.REACT_ROUTER_HONO_SERVER_BASENAME": JSON.stringify(pluginConfig.basename)
49
50
  },
50
51
  ssr: {
51
52
  target: runtime === "cloudflare" ? "webworker" : void 0,
@@ -64,6 +65,8 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
64
65
  return {
65
66
  ...baseConfig,
66
67
  build: {
68
+ // https://vite.dev/config/build-options#build-target
69
+ cssTarget: ["es2020", "edge88", "firefox78", "chrome87", "safari14"],
67
70
  target: "esnext",
68
71
  rollupOptions: {
69
72
  input: pluginConfig.serverEntryPoint,
@@ -101,11 +104,11 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
101
104
  entry: pluginConfig.serverEntryPoint,
102
105
  export: "default",
103
106
  exclude: [
104
- `/${pluginConfig.appDirectory}/**/*`,
105
- `/${pluginConfig.appDirectory}/**/.*/**`,
107
+ /.*\.(ts|js|tsx|jsx|css)(\?.*)?$/,
108
+ /\?import(\?.*)?$/,
106
109
  /^\/@.+$/,
107
110
  /^\/node_modules\/.*/,
108
- /\?import$/,
111
+ `/${pluginConfig.appDirectory}/**/.*/**`,
109
112
  ...pluginConfig.dev?.exclude || []
110
113
  ]
111
114
  });
@@ -136,6 +139,7 @@ function resolvePluginConfig(config, options) {
136
139
  const assetsDir = config.build?.assetsDir || "assets";
137
140
  const serverEntryPoint = options.serverEntryPoint || findDefaultServerEntry(appDirectory);
138
141
  const serverBuildFile = reactRouterConfig.reactRouterConfig.serverBuildFile;
142
+ const basename = reactRouterConfig.reactRouterConfig.basename;
139
143
  return {
140
144
  rootDirectory,
141
145
  buildDirectory,
@@ -144,7 +148,8 @@ function resolvePluginConfig(config, options) {
144
148
  assetsDir,
145
149
  serverEntryPoint,
146
150
  dev: options.dev,
147
- serverBuildFile
151
+ serverBuildFile,
152
+ basename
148
153
  };
149
154
  }
150
155
  var warned = false;
@@ -1,11 +1,15 @@
1
+ import * as react_router from 'react-router';
2
+ import { ServerBuild, AppLoadContext } from 'react-router';
3
+ import * as hono from 'hono';
1
4
  import { Env, Hono, Context } from 'hono';
2
- import { HonoOptions } from 'hono/hono-base';
3
5
  import { UpgradeWebSocket } from 'hono/ws';
4
- import { ServerBuild, AppLoadContext } from 'react-router';
5
6
 
6
7
  interface HonoServerOptionsBase<E extends Env> {
7
8
  /**
8
- * Hono app to use
9
+ * The base Hono app to use as a replacement for the default one created automatically
10
+ *
11
+ * It will be used to mount the React Router server on the `basename` path
12
+ * defined in the [React Router config](https://api.reactrouter.com/v7/types/_react_router_dev.config.Config.html)
9
13
  *
10
14
  * {@link Hono}
11
15
  */
@@ -44,9 +48,11 @@ interface HonoServerOptionsBase<E extends Env> {
44
48
  }
45
49
  ) => Promise<AppLoadContext> | AppLoadContext;
46
50
  /**
47
- * @deprecated Use `app` instead
51
+ * Hook to add middleware that runs before any built-in middleware, including assets serving.
52
+ *
53
+ * You can use it to add protection middleware, for example.
48
54
  */
49
- honoOptions?: HonoOptions<E>;
55
+ beforeAll?: (app: Hono<E>) => Promise<void> | void;
50
56
  }
51
57
 
52
58
  interface WithWebsocket<E extends Env> {
@@ -83,4 +89,12 @@ interface WithoutWebsocket<E extends Env> {
83
89
  configure?: (app: Hono<E>) => Promise<void> | void;
84
90
  }
85
91
 
86
- export type { HonoServerOptionsBase as H, WithWebsocket as W, WithoutWebsocket as a };
92
+ /**
93
+ * Helper to create a getLoadContext function fully typed
94
+ */
95
+ declare function createGetLoadContext(getLoadContext: HonoServerOptionsBase<Env>["getLoadContext"]): ((c: hono.Context, options: {
96
+ build: ServerBuild;
97
+ mode: string;
98
+ }) => Promise<react_router.AppLoadContext> | react_router.AppLoadContext) | undefined;
99
+
100
+ export { type HonoServerOptionsBase as H, type WithWebsocket as W, type WithoutWebsocket as a, createGetLoadContext as c };
package/dist/http.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Redirect to a new location in a way that React Router can handle.
3
+ *
4
+ * It follows the Single Fetch Redirect protocol.
5
+ */
6
+ declare function reactRouterRedirect(location: string): Response;
7
+
8
+ export { reactRouterRedirect };
package/dist/http.js ADDED
@@ -0,0 +1,43 @@
1
+ // src/http.ts
2
+ function reactRouterRedirect(location) {
3
+ return new Response(
4
+ new ReadableStream({
5
+ start(controller) {
6
+ controller.enqueue(
7
+ JSON.stringify([
8
+ ["SingleFetchRedirect", 1],
9
+ {
10
+ _2: 3,
11
+ _4: 5,
12
+ _6: 7,
13
+ _8: 9,
14
+ _10: 7
15
+ },
16
+ "redirect",
17
+ location,
18
+ "status",
19
+ 302,
20
+ "revalidate",
21
+ false,
22
+ "reload",
23
+ true,
24
+ "replace"
25
+ ])
26
+ );
27
+ controller.close();
28
+ }
29
+ }),
30
+ {
31
+ status: 202,
32
+ headers: {
33
+ Location: location,
34
+ "X-Remix-Reload-Document": "yes",
35
+ "X-Remix-Response": "yes",
36
+ "Content-Type": "text/x-script"
37
+ }
38
+ }
39
+ );
40
+ }
41
+ export {
42
+ reactRouterRedirect
43
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-router-hono-server",
3
- "version": "2.4.0",
3
+ "version": "2.6.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": {
@@ -38,6 +38,13 @@
38
38
  "types": "./dist/middlewares.d.ts",
39
39
  "default": "./dist/middlewares.js"
40
40
  }
41
+ },
42
+ "./http": {
43
+ "import": {
44
+ "import": "./dist/http.js",
45
+ "types": "./dist/http.d.ts",
46
+ "default": "./dist/http.js"
47
+ }
41
48
  }
42
49
  },
43
50
  "scripts": {
@@ -89,10 +96,10 @@
89
96
  "vitest": "^2.1.5"
90
97
  },
91
98
  "peerDependencies": {
92
- "react-router": "^7.0.1",
93
- "vite": "^5.4.0"
99
+ "react-router": "^7.1.0",
100
+ "vite": "^5.1.0 || ^6.0.0"
94
101
  },
95
102
  "engines": {
96
- "node": ">=20.0.0"
103
+ "node": ">=22.12.0"
97
104
  }
98
105
  }