react-router-hono-server 2.3.0 → 2.5.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
@@ -442,6 +442,24 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
442
442
  * For example, you can use this to bind `@hono/node-ws`'s `injectWebSocket`
443
443
  */
444
444
  onServe?: (server: ServerType) => void;
445
+ /**
446
+ * The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance.
447
+ *
448
+ * If you want this behavior, set it to `true`
449
+ *
450
+ * 🚨 Setting this to `true` can break `request.clone()` if you later check `instanceof Request`.
451
+ *
452
+ * {@link https://github.com/honojs/node-server?tab=readme-ov-file#overrideglobalobjects}
453
+ *
454
+ * @default false
455
+ */
456
+ overrideGlobalObjects?: boolean;
457
+ /**
458
+ * Hook to add middleware that runs before any built-in middleware, including assets serving.
459
+ *
460
+ * You can use it to add protection middleware, for example.
461
+ */
462
+ beforeAll?: (app: Hono<E>) => Promise<void> | void;
445
463
  }
446
464
  ```
447
465
 
@@ -454,16 +472,34 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
454
472
  * {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
455
473
  */
456
474
  customBunServer?: Serve & ServeOptions;
475
+ /**
476
+ * Hook to add middleware that runs before any built-in middleware, including assets serving.
477
+ *
478
+ * You can use it to add protection middleware, for example.
479
+ */
480
+ beforeAll?: (app: Hono<E>) => Promise<void> | void;
457
481
  }
458
482
  ```
459
483
 
460
484
  ##### Cloudflare Workers
461
485
  ```ts
462
- export interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {}
486
+ export interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port" | "beforeAll"> {}
463
487
  ```
464
488
 
465
489
  ## Middleware
466
490
 
491
+ 🚨 Redirecting from a middleware
492
+ > [!IMPORTANT]
493
+ > You **have to** use the `reactRouterRedirect` helper to redirect from a middleware.
494
+ >
495
+ > It returns a single-fetch-like response.
496
+ >
497
+ > If you use `c.redirect`, it will not work as expected and you will get a `Unable to decode turbo-stream response` error.
498
+ >
499
+ >```ts
500
+ > import { reactRouterRedirect } from "react-router-hono-server/http";
501
+ >```
502
+
467
503
  Middleware are functions that are called before React Router calls your loader/action.
468
504
 
469
505
  Hono is the perfect tool for this, as it supports middleware out of the box.
@@ -477,6 +513,31 @@ See how [Shelf.nu](https://github.com/Shelf-nu/shelf.nu/blob/main/server/middlew
477
513
  > [!TIP]
478
514
  > This lib exports one middleware `cache` (`react-router-hono-server/middleware`) that you can use to cache your responses.
479
515
 
516
+ ### `beforeAll`
517
+ You can use the `beforeAll` option to add middleware that runs before any built-in middleware, including assets serving.
518
+
519
+ You can use it to add protection middleware, for example.
520
+
521
+ > [!TIP]
522
+ > When you check the path to protect, don't forget to use `c.req.path.includes("")` to handle `.data` requests (`loader`)!
523
+
524
+ ```ts
525
+ import { reactRouterRedirect } from "react-router-hono-server/http";
526
+ import { createHonoServer } from "react-router-hono-server/node";
527
+
528
+ export default await createHonoServer({
529
+ beforeAll(app) {
530
+ app.use(async (c, next) => {
531
+ if (c.req.path.includes("/protected") && !c.req.header("Authorization")) {
532
+ return reactRouterRedirect("/login");
533
+ }
534
+
535
+ return next();
536
+ });
537
+ },
538
+ });
539
+ ```
540
+
480
541
  ### Using remix-hono middleware
481
542
 
482
543
  It is easy to use [remix-hono](https://github.com/sergiodxa/remix-hono) middleware with this package.
@@ -1,7 +1,7 @@
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';
4
+ import { W as WithWebsocket, a as WithoutWebsocket, H as HonoServerOptionsBase } from '../hono-server-options-base.d-CPG630Yc.js';
5
5
  import 'hono/hono-base';
6
6
  import 'hono/ws';
7
7
  import 'react-router';
@@ -1,8 +1,9 @@
1
1
  import {
2
+ bindIncomingRequestSocketInfo,
2
3
  cleanUpgradeListeners,
3
4
  createWebSocket,
4
5
  patchUpgradeListener
5
- } from "../chunk-27A6I7NN.js";
6
+ } from "../chunk-D4WESSFB.js";
6
7
  import {
7
8
  cache
8
9
  } from "../chunk-V3H4JZ4H.js";
@@ -27,6 +28,10 @@ async function createHonoServer(options) {
27
28
  app,
28
29
  enabled: mergedOptions.useWebSocket ?? false
29
30
  });
31
+ if (!PRODUCTION) {
32
+ app.use(bindIncomingRequestSocketInfo());
33
+ }
34
+ await mergedOptions.beforeAll?.(app);
30
35
  app.use(
31
36
  `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
32
37
  cache(60 * 60 * 24 * 365),
@@ -42,11 +47,11 @@ async function createHonoServer(options) {
42
47
  } else {
43
48
  await mergedOptions.configure?.(app);
44
49
  }
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
+ );
45
54
  app.use(async (c, next) => {
46
- const build = await import(
47
- // @ts-expect-error - Virtual module provided by React Router at build time
48
- "virtual:react-router/server-build"
49
- );
50
55
  return createMiddleware(async (c2) => {
51
56
  const requestHandler = createRequestHandler(build, mode);
52
57
  const loadContext = mergedOptions.getLoadContext?.(c2, { build, mode });
@@ -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';
4
+ import { a as WithoutWebsocket, H as HonoServerOptionsBase } from '../hono-server-options-base.d-CPG630Yc.js';
5
5
  import 'hono/hono-base';
6
6
  import 'hono/ws';
7
7
  import 'react-router';
8
8
 
9
- interface HonoCloudflareOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
9
+ interface HonoCloudflareOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port" | "beforeAll"> {
10
10
  }
11
11
  type HonoServerOptions<E extends Env = BlankEnv> = HonoCloudflareOptions<E> & Omit<WithoutWebsocket<E>, "useWebSocket">;
12
12
  /**
@@ -1,3 +1,6 @@
1
+ import {
2
+ bindIncomingRequestSocketInfo
3
+ } from "../chunk-D4WESSFB.js";
1
4
  import {
2
5
  cache
3
6
  } from "../chunk-V3H4JZ4H.js";
@@ -18,16 +21,17 @@ async function createHonoServer(options) {
18
21
  if (DEV) {
19
22
  const { serveStatic } = await import("@hono/node-server/serve-static");
20
23
  app.use("*", cache(60 * 60), serveStatic({ root: "./public" }));
24
+ app.use(bindIncomingRequestSocketInfo());
21
25
  }
22
26
  if (mergedOptions.defaultLogger) {
23
27
  app.use("*", logger());
24
28
  }
25
29
  await mergedOptions.configure?.(app);
30
+ const build = await import(
31
+ // @ts-expect-error - Virtual module provided by React Router at build time
32
+ "virtual:react-router/server-build"
33
+ );
26
34
  app.use(async (c, next) => {
27
- const build = await import(
28
- // @ts-expect-error - Virtual module provided by React Router at build time
29
- "virtual:react-router/server-build"
30
- );
31
35
  return createMiddleware(async (c2) => {
32
36
  const requestHandler = createRequestHandler(build, mode);
33
37
  const loadContext = mergedOptions.getLoadContext?.(c2, { build, mode });
@@ -2,7 +2,7 @@ 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 '../hono-server-options-base.d-CPG630Yc.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';
@@ -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,8 +1,9 @@
1
1
  import {
2
+ bindIncomingRequestSocketInfo,
2
3
  cleanUpgradeListeners,
3
4
  createWebSocket,
4
5
  patchUpgradeListener
5
- } from "../chunk-27A6I7NN.js";
6
+ } from "../chunk-D4WESSFB.js";
6
7
  import {
7
8
  cache
8
9
  } from "../chunk-V3H4JZ4H.js";
@@ -22,7 +23,8 @@ async function createHonoServer(options) {
22
23
  console.log(`\u{1F30D} http://127.0.0.1:${info.port}`);
23
24
  }),
24
25
  port: options?.port || Number(process.env.PORT) || 3e3,
25
- defaultLogger: options?.defaultLogger ?? true
26
+ defaultLogger: options?.defaultLogger ?? true,
27
+ overrideGlobalObjects: options?.overrideGlobalObjects ?? false
26
28
  };
27
29
  const mode = import.meta.env.MODE || "production";
28
30
  const PRODUCTION = mode === "production";
@@ -32,6 +34,10 @@ async function createHonoServer(options) {
32
34
  app,
33
35
  enabled: mergedOptions.useWebSocket ?? false
34
36
  });
37
+ if (!PRODUCTION) {
38
+ app.use(bindIncomingRequestSocketInfo());
39
+ }
40
+ await mergedOptions.beforeAll?.(app);
35
41
  app.use(
36
42
  `/${import.meta.env.REACT_ROUTER_HONO_SERVER_ASSETS_DIR}/*`,
37
43
  cache(60 * 60 * 24 * 365),
@@ -47,11 +53,11 @@ async function createHonoServer(options) {
47
53
  } else {
48
54
  await mergedOptions.configure?.(app);
49
55
  }
56
+ const build = await import(
57
+ // @ts-expect-error - Virtual module provided by React Router at build time
58
+ "virtual:react-router/server-build"
59
+ );
50
60
  app.use(async (c, next) => {
51
- const build = await import(
52
- // @ts-expect-error - Virtual module provided by React Router at build time
53
- "virtual:react-router/server-build"
54
- );
55
61
  return createMiddleware(async (c2) => {
56
62
  const requestHandler = createRequestHandler(build, mode);
57
63
  const loadContext = mergedOptions.getLoadContext?.(c2, { build, mode });
@@ -63,7 +69,8 @@ async function createHonoServer(options) {
63
69
  {
64
70
  ...app,
65
71
  ...mergedOptions.customNodeServer,
66
- port: mergedOptions.port
72
+ port: mergedOptions.port,
73
+ overrideGlobalObjects: mergedOptions.overrideGlobalObjects
67
74
  },
68
75
  mergedOptions.listeningListener
69
76
  );
@@ -1,4 +1,5 @@
1
1
  // src/helpers.ts
2
+ import { createMiddleware } from "hono/factory";
2
3
  var defaultWebSocket = {
3
4
  upgradeWebSocket: () => async () => {
4
5
  },
@@ -63,9 +64,24 @@ function patchUpgradeListener(httpServer) {
63
64
  });
64
65
  }
65
66
  }
67
+ function bindIncomingRequestSocketInfo() {
68
+ return createMiddleware(async (c, next) => {
69
+ c.env.server = {
70
+ incoming: {
71
+ socket: {
72
+ remoteAddress: c.req.raw.headers.get("x-remote-address") || void 0,
73
+ remotePort: Number(c.req.raw.headers.get("x-remote-port")) || void 0,
74
+ remoteFamily: c.req.raw.headers.get("x-remote-family") || void 0
75
+ }
76
+ }
77
+ };
78
+ return next();
79
+ });
80
+ }
66
81
 
67
82
  export {
68
83
  createWebSocket,
69
84
  cleanUpgradeListeners,
70
- patchUpgradeListener
85
+ patchUpgradeListener,
86
+ bindIncomingRequestSocketInfo
71
87
  };
package/dist/dev.js CHANGED
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import honoDevServer from "@hono/vite-dev-server";
5
5
  import bunAdapter from "@hono/vite-dev-server/bun";
6
6
  import cloudflareAdapter from "@hono/vite-dev-server/cloudflare";
7
+ import nodeAdapter from "@hono/vite-dev-server/node";
7
8
  var virtualModuleId = "\0virtual:react-router-hono-server/server";
8
9
  function reactRouterHonoServer(options = {}) {
9
10
  const runtime = options.runtime || "node";
@@ -63,6 +64,8 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
63
64
  return {
64
65
  ...baseConfig,
65
66
  build: {
67
+ // https://vite.dev/config/build-options#build-target
68
+ cssTarget: ["es2020", "edge88", "firefox78", "chrome87", "safari14"],
66
69
  target: "esnext",
67
70
  rollupOptions: {
68
71
  input: pluginConfig.serverEntryPoint,
@@ -87,7 +90,7 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
87
90
  if (devServerPlugin) {
88
91
  return;
89
92
  }
90
- let adapter;
93
+ let adapter = nodeAdapter;
91
94
  if (runtime === "bun") {
92
95
  adapter = bunAdapter;
93
96
  }
@@ -108,6 +111,12 @@ Please add it to your plugins: import { cloudflareDevProxy } from "@react-router
108
111
  ...pluginConfig.dev?.exclude || []
109
112
  ]
110
113
  });
114
+ server.middlewares.use((req, _res, next) => {
115
+ req.rawHeaders.push("x-remote-address", req.socket.remoteAddress || "unknown");
116
+ req.rawHeaders.push("x-remote-port", String(req.socket.remotePort || "unknown"));
117
+ req.rawHeaders.push("x-remote-family", req.socket.remoteFamily || "unknown");
118
+ next();
119
+ });
111
120
  if (typeof devServerPlugin.configureServer === "function") {
112
121
  devServerPlugin.configureServer(server);
113
122
  } else {
@@ -47,6 +47,12 @@ interface HonoServerOptionsBase<E extends Env> {
47
47
  * @deprecated Use `app` instead
48
48
  */
49
49
  honoOptions?: HonoOptions<E>;
50
+ /**
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.
54
+ */
55
+ beforeAll?: (app: Hono<E>) => Promise<void> | void;
50
56
  }
51
57
 
52
58
  interface WithWebsocket<E extends Env> {
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.3.0",
3
+ "version": "2.5.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": {