react-router-hono-server 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Raphael Moreau (@rphlmr)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,302 @@
1
+ # React Router Hono Server
2
+
3
+ Inspired by [remix-express-vite-plugin](https://github.com/kiliman/remix-express-vite-plugin) from [@kiliman](https://github.com/kiliman)
4
+
5
+ <!-- ![GitHub Repo stars](https://img.shields.io/github/stars/rphlmr/react-router-hono-server?style=social)
6
+ ![npm](https://img.shields.io/npm/v/open-source-stack?style=plastic)
7
+ ![GitHub](https://img.shields.io/github/license/rphlmr/react-router-hono-server?style=plastic)
8
+ ![npm](https://img.shields.io/npm/dy/open-source-stack?style=plastic)
9
+ ![npm](https://img.shields.io/npm/dw/open-source-stack?style=plastic)
10
+ ![GitHub top language](https://img.shields.io/github/languages/top/rphlmr/react-router-hono-server?style=plastic) -->
11
+
12
+ This package contains a helper function that enables you to create your Hono
13
+ server directly from you _entry.server.tsx_. Since the Hono server is built along
14
+ with the rest of your Remix app, you may import app modules as needed. It also
15
+ supports Vite HMR via the `react-router-hono-server/dev` plugin (which is required
16
+ for this to function).
17
+
18
+ > [!IMPORTANT]
19
+ > Only works with Remix in **ESM mode**
20
+ >
21
+ > Only works with **Vite**
22
+ >
23
+ > Only works for **node**
24
+
25
+ > [!TIP]
26
+ > Install [remix-hono](https://github.com/sergiodxa/remix-hono) to add cool middlewares like [`session`](https://github.com/sergiodxa/remix-hono?tab=readme-ov-file#session-management)
27
+
28
+ ## Installation
29
+
30
+ Install the following npm package. NOTE: This is not a dev dependency, as it
31
+ creates the Hono server used in production.
32
+
33
+ ```bash
34
+ npm install hono remix-hono react-router-hono-server
35
+ ```
36
+
37
+ ## Configuration
38
+ ### Create the server
39
+ From your _entry.server.tsx_ file, export the server from `createHonoServer` and
40
+ name it `server` or the name you defined in `devServer({exportName})` in your _vite.config.ts_.
41
+
42
+ ```ts
43
+ // app/entry.server.tsx
44
+
45
+ import { createHonoServer } from "react-router-hono-server/node";
46
+
47
+ export const server = await createHonoServer();
48
+ ```
49
+
50
+ ### Add the Vite plugin
51
+ ```ts
52
+ // vite.config.ts
53
+
54
+ import { vitePlugin as remix } from "@remix-run/dev";
55
+ import { installGlobals } from "@remix-run/node";
56
+ import { devServer } from "react-router-hono-server/dev";
57
+ import { defineConfig } from "vite";
58
+ import tsconfigPaths from "vite-tsconfig-paths";
59
+
60
+ installGlobals();
61
+
62
+ export default defineConfig({
63
+ build: {
64
+ target: "esnext",
65
+ },
66
+ plugins: [devServer(), remix(), tsconfigPaths()],
67
+ });
68
+ ```
69
+
70
+ ### Update package.json scripts
71
+ ```json
72
+ "scripts": {
73
+ "build": "NODE_ENV=production remix vite:build",
74
+ "dev": "vite --host",
75
+ "start": "NODE_ENV=production node ./build/server/index.js"
76
+ },
77
+ ```
78
+
79
+ ## How it works
80
+
81
+ This helper function works differently depending on the environment.
82
+
83
+ For `development`, it creates an Hono server that the Vite plugin will load
84
+ via `viteDevServer.ssrLoadModule('virtual:remix/server-build')`.
85
+ The actual server is controlled by Vite through `@hono/vite-dev-server`, and can be configured via _vite.config.ts_ `server` options.
86
+
87
+ For `production`, it will create a standard node HTTP server listening at `HOST:PORT`.
88
+ You can customize the production server port using the `port` option of `createHonoServer`.
89
+
90
+ When building for production, the Hono server is compiled in the same bundle as the rest of your Remix app, you can import app modules just like you normally would.
91
+
92
+ To run the server in production, use `NODE_ENV=production node ./build/server/index.js`.
93
+
94
+ That's all!
95
+
96
+ ### Options
97
+
98
+ ```ts
99
+ export type HonoServerOptions = {
100
+ /**
101
+ * Enable the default logger
102
+ *
103
+ * Defaults to `true`
104
+ */
105
+ defaultLogger?: boolean;
106
+ /**
107
+ * The port to start the server on
108
+ *
109
+ * Defaults to `process.env.PORT || 3000`
110
+ */
111
+ port?: number;
112
+ /**
113
+ * The directory where the server build files are located (defined in vite.config)
114
+ *
115
+ * Defaults to `build/server`
116
+ *
117
+ * See https://remix.run/docs/en/main/file-conventions/vite-config#builddirectory
118
+ */
119
+ buildDirectory?: string;
120
+ /**
121
+ * The file name of the server build file (defined in vite.config)
122
+ *
123
+ * Defaults to `index.js`
124
+ *
125
+ * See https://remix.run/docs/en/main/file-conventions/vite-config#serverbuildfile
126
+ */
127
+ serverBuildFile?: `${string}.js`;
128
+ /**
129
+ * The directory where the assets are located (defined in vite.config, build.assetsDir)
130
+ *
131
+ * Defaults to `assets`
132
+ *
133
+ * See https://vitejs.dev/config/build-options#build-assetsdir
134
+ */
135
+ assetsDir?: string;
136
+ /**
137
+ * Customize the Hono server, for example, adding middlewares
138
+ *
139
+ * It is applied after the default middlewares and before the remix middleware
140
+ */
141
+ configure?: (server: Hono) => Promise<void> | void;
142
+ /**
143
+ * Augment the Remix AppLoadContext
144
+ *
145
+ * Don't forget to declare the AppLoadContext in your app, next to where you create the Hono server
146
+ *
147
+ * ```ts
148
+ * declare module "@remix-run/node" {
149
+ * interface AppLoadContext {
150
+ * // Add your custom context here
151
+ * }
152
+ * }
153
+ * ```
154
+ */
155
+ getLoadContext?: (
156
+ c: Context,
157
+ options: Pick<RemixMiddlewareOptions, "build" | "mode">
158
+ ) => Promise<AppLoadContext> | AppLoadContext;
159
+ /**
160
+ * Listening listener (production mode only)
161
+ *
162
+ * It is called when the server is listening
163
+ *
164
+ * Defaults log the port
165
+ */
166
+ listeningListener?: (info: { port: number }) => void;
167
+ };
168
+ ```
169
+
170
+ You can add additional Hono middleware with the `configure` function. If you
171
+ do not provide a function, it will create a default Hono server.
172
+ The `configure` function can be async. So, make sure to `await createHonoServer()`.
173
+
174
+ If you want to set up the Remix `AppLoadContext`, pass in a function to `getLoadContext`.
175
+ Modify the `AppLoadContext` interface used in your app.
176
+
177
+ Since the Hono server is compiled in the same bundle as the rest of your Remix
178
+ app, you can import app modules just like you normally would.
179
+
180
+ ### Example
181
+
182
+ ```ts
183
+ // app/entry.server.tsx
184
+
185
+ import { createHonoServer } from "react-router-hono-server/node";
186
+
187
+ /**
188
+ * Declare our loaders and actions context type
189
+ */
190
+ declare module "@remix-run/node" {
191
+ interface AppLoadContext {
192
+ /**
193
+ * The app version from the build assets
194
+ */
195
+ readonly appVersion: string;
196
+ }
197
+ }
198
+
199
+ export const server = await createHonoServer({
200
+ getLoadContext(_, { build, mode }) {
201
+ const isProductionMode = mode === "production";
202
+ return {
203
+ appVersion: isProductionMode ? build.assets.version : "dev",
204
+ };
205
+ },
206
+ });
207
+ ```
208
+
209
+ ```ts
210
+ // app/routes/test.tsx
211
+
212
+ export async function loader({ context }: LoaderFunctionArgs) {
213
+ // get the context provided from `getLoadContext`
214
+ return { appVersion: context.appVersion }
215
+ }
216
+ ```
217
+
218
+ ## Middlewares
219
+
220
+ Middlewares are functions that are called before Remix calls your loader/action.
221
+
222
+ Hono is the perfect tool for this, as it supports middleware out of the box.
223
+
224
+ See the [Hono docs](https://hono.dev/docs/guides/middleware) for more information.
225
+
226
+ You can imagine many use cases for middlewares, such as authentication, protecting routes, caching, logging, etc.
227
+
228
+ See how [Shelf.nu](https://github.com/Shelf-nu/shelf.nu/blob/main/server/middleware.ts) uses them!
229
+
230
+ > [!TIP]
231
+ > This lib exports one middleware `cache` (`react-router-hono-server/middlewares`) that you can use to cache your responses.
232
+
233
+ ### Using Remix Hono middlewares
234
+
235
+ It is easy to use [remix-hono](https://github.com/sergiodxa/remix-hono) middlewares with this package.
236
+
237
+ ```ts
238
+ import { createCookieSessionStorage } from "@remix-run/node";
239
+ import { createHonoServer } from "react-router-hono-server/node";
240
+ import { session } from "remix-hono/session";
241
+
242
+ export const server = await createHonoServer({
243
+ configure: (server) => {
244
+ server.use(
245
+ session({
246
+ autoCommit: true,
247
+ createSessionStorage() {
248
+ const sessionStorage = createCookieSessionStorage({
249
+ cookie: {
250
+ name: "session",
251
+ httpOnly: true,
252
+ path: "/",
253
+ sameSite: "lax",
254
+ secrets: [process.env.SESSION_SECRET],
255
+ secure: process.env.NODE_ENV === "production",
256
+ },
257
+ });
258
+
259
+ return {
260
+ ...sessionStorage,
261
+ // If a user doesn't come back to the app within 30 days, their session will be deleted.
262
+ async commitSession(session) {
263
+ return sessionStorage.commitSession(session, {
264
+ maxAge: 60 * 60 * 24 * 30, // 30 days
265
+ });
266
+ },
267
+ };
268
+ },
269
+ })
270
+ );
271
+ },
272
+ });
273
+ ```
274
+
275
+
276
+ ### Creating custom Middleware
277
+
278
+ You can create middlewares using the [`createMiddleware`](https://hono.dev/docs/helpers/factory#createmiddleware) or [`createFactory`](https://hono.dev/docs/helpers/factory#createfactory) functions from `hono/factory`.
279
+
280
+ Then, use them with the `configure` function of `createHonoServer`.
281
+
282
+ ```ts
283
+ import { createMiddleware } from "hono/factory";
284
+ import { createHonoServer } from "react-router-hono-server/node";
285
+
286
+ export const server = await createHonoServer({
287
+ configure: (server) => {
288
+ server.use(
289
+ createMiddleware(async (c, next) => {
290
+ console.log("middleware");
291
+ return next();
292
+ })
293
+ );
294
+ },
295
+ });
296
+ ```
297
+
298
+ ## Contributors ✨
299
+
300
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
301
+
302
+ This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
@@ -0,0 +1 @@
1
+ import{createMiddleware as t}from"hono/factory";function n(a){return t(async(e,r)=>{if(!e.req.path.match(/\.[a-zA-Z0-9]+$/)||e.req.path.endsWith(".data"))return r();await r(),e.res.ok&&e.res.headers.set("cache-control",`public, max-age=${a}`)})}export{n as a};
package/dist/dev.d.mts ADDED
@@ -0,0 +1,41 @@
1
+ import * as vite from 'vite';
2
+
3
+ type HonoDevServerOptions = {
4
+ /**
5
+ * The path to the `app` directory, relative to `vite.config.ts`.
6
+ *
7
+ * Defaults to `"app"`.
8
+ */
9
+ appDirectory?: string;
10
+ /**
11
+ * The path to the entry file, relative to `vite.config.ts`.
12
+ *
13
+ * Defaults to `"app/entry.server.tsx"`.
14
+ */
15
+ entry?: string;
16
+ /**
17
+ * The name of the export from the entry file.
18
+ *
19
+ * Defaults to `server`. If you are using export default, use `default`
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * export const server = createHonoServer();
24
+ * ```
25
+ */
26
+ exportName?: string;
27
+ /**
28
+ * The paths that are not served by the dev-server.
29
+ *
30
+ * Defaults include `appDirectory` content.
31
+ */
32
+ exclude?: string[];
33
+ };
34
+ /**
35
+ * Create a dev server for the Hono server
36
+ *
37
+ * @param config {@link HonoDevServerOptions} - The configuration options for the dev server
38
+ */
39
+ declare function devServer(config?: HonoDevServerOptions): vite.Plugin<any>;
40
+
41
+ export { devServer };
package/dist/dev.mjs ADDED
@@ -0,0 +1 @@
1
+ import t from"@hono/vite-dev-server";var o={entry:"app/entry.server.tsx",exportName:"server",appDirectory:"app",exclude:[]};function p(r){let e={...o,...r};return t({injectClientScript:!1,entry:e.entry,export:e.exportName,exclude:[`/${e.appDirectory}/**`,/^\/@.+$/,/^\/node_modules\/.*/,...e.exclude]})}export{p as devServer};
@@ -0,0 +1,10 @@
1
+ import * as hono from 'hono';
2
+
3
+ /**
4
+ * Cache middleware
5
+ *
6
+ * @param seconds - The number of seconds to cache
7
+ */
8
+ declare function cache(seconds: number): hono.MiddlewareHandler<any, string, {}>;
9
+
10
+ export { cache };
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-4CKI2DYM.mjs";export{a as cache};
@@ -0,0 +1,81 @@
1
+ import * as hono_types from 'hono/types';
2
+ import { AppLoadContext } from '@remix-run/node';
3
+ import { Hono, Context } from 'hono';
4
+ import { RemixMiddlewareOptions } from 'remix-hono/handler';
5
+
6
+ type HonoServerOptions = {
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
+ * The directory where the server build files are located (defined in vite.config)
21
+ *
22
+ * Defaults to `build/server`
23
+ *
24
+ * See https://remix.run/docs/en/main/file-conventions/vite-config#builddirectory
25
+ */
26
+ buildDirectory?: string;
27
+ /**
28
+ * The file name of the server build file (defined in vite.config)
29
+ *
30
+ * Defaults to `index.js`
31
+ *
32
+ * See https://remix.run/docs/en/main/file-conventions/vite-config#serverbuildfile
33
+ */
34
+ serverBuildFile?: `${string}.js`;
35
+ /**
36
+ * The directory where the assets are located (defined in vite.config, build.assetsDir)
37
+ *
38
+ * Defaults to `assets`
39
+ *
40
+ * See https://vitejs.dev/config/build-options#build-assetsdir
41
+ */
42
+ assetsDir?: string;
43
+ /**
44
+ * Customize the Hono server, for example, adding middlewares
45
+ *
46
+ * It is applied after the default middlewares and before the remix middleware
47
+ */
48
+ configure?: (server: Hono) => Promise<void> | void;
49
+ /**
50
+ * Augment the Remix AppLoadContext
51
+ *
52
+ * Don't forget to declare the AppLoadContext in your app, next to where you create the Hono server
53
+ *
54
+ * ```ts
55
+ * declare module "@remix-run/node" {
56
+ * interface AppLoadContext {
57
+ * // Add your custom context here
58
+ * }
59
+ * }
60
+ * ```
61
+ */
62
+ getLoadContext?: (c: Context, options: Pick<RemixMiddlewareOptions, "build" | "mode">) => Promise<AppLoadContext> | AppLoadContext;
63
+ /**
64
+ * Listening listener (production mode only)
65
+ *
66
+ * It is called when the server is listening
67
+ *
68
+ * Defaults log the port
69
+ */
70
+ listeningListener?: (info: {
71
+ port: number;
72
+ }) => void;
73
+ };
74
+ /**
75
+ * Create a Hono server
76
+ *
77
+ * @param config {@link HonoServerOptions} - The configuration options for the server
78
+ */
79
+ declare function createHonoServer(options?: HonoServerOptions): Promise<Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">>;
80
+
81
+ export { type HonoServerOptions, createHonoServer };
package/dist/node.mjs ADDED
@@ -0,0 +1 @@
1
+ import{a as i}from"./chunk-4CKI2DYM.mjs";import d from"node:path";import v from"node:url";import{serve as g}from"@hono/node-server";import{serveStatic as u}from"@hono/node-server/serve-static";import{Hono as f}from"hono";import{logger as x}from"hono/logger";import{remix as L}from"remix-hono/handler";var c=process.env.NODE_ENV==="production"?void 0:await import("vite").then(o=>o.createServer({server:{middlewareMode:!0},appType:"custom"}));async function p(){return c?.ssrLoadModule("virtual:remix/server-build")}var b={defaultLogger:!0,port:Number(process.env.PORT)||3e3,buildDirectory:"build/server",serverBuildFile:"index.js",assetsDir:"assets",listeningListener:o=>{console.log(`\u{1F680} Server started on port ${o.port}`)}};async function M(o={}){let e={...b,...o,defaultLogger:o.defaultLogger??!0},n=process.env.NODE_ENV==="test"?"development":process.env.NODE_ENV,t=n==="production",r=new f;return r.use(`/${e.assetsDir}/*`,i(60*60*24*365),u({root:"./build/client"})),r.use("*",i(60*60),u({root:t?"./build/client":"./public"})),e.defaultLogger&&r.use("*",x()),e.configure&&await e.configure(r),r.use(async(l,a)=>{let s=t?await import(v.pathToFileURL(d.resolve(d.join(process.cwd(),`./${e.buildDirectory}/${e.serverBuildFile}`))).toString()):await p();return L({build:s,mode:n,getLoadContext(m){return e.getLoadContext?e.getLoadContext(m,{build:s}):{}}})(l,a)}),t&&g({...r,port:e.port},e.listeningListener),r}export{M as createHonoServer};
package/package.json ADDED
@@ -0,0 +1,83 @@
1
+ {
2
+ "name": "react-router-hono-server",
3
+ "version": "0.0.1",
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.",
5
+ "exports": {
6
+ "./node": {
7
+ "import": {
8
+ "import": "./dist/node.mjs",
9
+ "default": "./dist/node.mjs",
10
+ "types": "./dist/node.d.mts"
11
+ }
12
+ },
13
+ "./dev": {
14
+ "import": {
15
+ "import": "./dist/dev.mjs",
16
+ "default": "./dist/dev.mjs",
17
+ "types": "./dist/dev.d.mts"
18
+ }
19
+ },
20
+ "./middlewares": {
21
+ "import": {
22
+ "import": "./dist/middlewares.mjs",
23
+ "default": "./dist/middlewares.mjs",
24
+ "types": "./dist/middlewares.d.mts"
25
+ }
26
+ }
27
+ },
28
+ "scripts": {
29
+ "test": "vitest run",
30
+ "test:cov": "vitest run --coverage",
31
+ "build": "tsup src/node.ts src/dev.ts src/middlewares.ts --dts --format esm --outDir dist --minify --clean --external '../build/server/index.js'",
32
+ "remix:dev": "npm run dev -w example",
33
+ "build:dev": "tsup src/node.ts src/dev.ts src/middlewares.ts --dts --format esm --outDir dist --external '../build/server/index.js'",
34
+ "build:dev:watch": "npm run build:dev -- --watch",
35
+ "dev": "npm-run-all -s build:dev -p remix:dev build:dev:watch",
36
+ "prepublishOnly": "npm run build",
37
+ "check": "biome check .",
38
+ "check:fix": "biome check --fix .",
39
+ "typecheck": "tsc",
40
+ "validate": "npm run check && npm run tsc"
41
+ },
42
+ "author": "",
43
+ "license": "ISC",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/rphlmr/react-router-hono-server.git"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/rphlmr/react-router-hono-server/issues"
50
+ },
51
+ "files": ["dist"],
52
+ "workspaces": [".", "example"],
53
+ "homepage": "https://github.com/rphlmr/react-router-hono-server#readme",
54
+ "dependencies": {
55
+ "@hono/node-server": "^1.12.0",
56
+ "@hono/vite-dev-server": "^0.13.1",
57
+ "@remix-run/node": "^2.11.0",
58
+ "hono": "^4.5.3",
59
+ "remix-hono": "^0.0.16",
60
+ "vite": "^5.3.5"
61
+ },
62
+ "devDependencies": {
63
+ "@biomejs/biome": "^1.8.3",
64
+ "@types/node": "^20.12.7",
65
+ "@vitest/coverage-v8": "^1.5.2",
66
+ "happy-dom": "^14.7.1",
67
+ "lefthook": "^1.7.2",
68
+ "npm-run-all": "^4.1.5",
69
+ "tsup": "^8.0.2",
70
+ "typescript": "^5.4.5",
71
+ "vitest": "^1.5.2"
72
+ },
73
+ "optionalDependencies": {
74
+ "@rollup/rollup-darwin-x64-gnu": "4.18.1",
75
+ "@rollup/rollup-darwin-x64-musl": "4.18.1",
76
+ "@rollup/rollup-linux-arm64-gnu": "4.18.1",
77
+ "@rollup/rollup-linux-x64-gnu": "^4.18.1",
78
+ "@rollup/rollup-linux-x64-musl": "^4.18.1",
79
+ "@rollup/rollup-win32-arm64-msvc": "4.18.1",
80
+ "@rollup/rollup-win32-x64-msvc": "4.18.1",
81
+ "@rollup/rollup-win32-x64-musl": "4.18.1"
82
+ }
83
+ }