Skip to content

Commit

Permalink
Vite 6 + Hono sub app + fixes (#50)
Browse files Browse the repository at this point in the history
* fix #49

* vite 6

* add createGetLoadContext helper

* fix dev server middleware issue + lost context

* fix Context is empty for nested routes #47

* handle rr basename and hono sub apps on all adapter

* add cloudflare static serving opt-in
  • Loading branch information
rphlmr authored Jan 5, 2025
1 parent 170396d commit e048945
Show file tree
Hide file tree
Showing 101 changed files with 17,768 additions and 8,611 deletions.
107 changes: 87 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,22 @@ main = "./build/server/index.js"
assets = { directory = "./build/client/" }
```
##### Custom assets serving
You can set Cloudflare `experimental_serve_directly` and delegate assets serving to Hono, like for Node and Bun.
> [!TIP]
> Check https://developers.cloudflare.com/workers/static-assets/binding/#experimental_serve_directly
> [!TIP]
> Check this [example](./examples/cloudflare/simple/) to see how to use it.
```toml
[assets]
directory = "./build/client/"
binding = "ASSETS"
experimental_serve_directly = false
```
## How it works
This helper works differently depending on the environment.
Expand Down Expand Up @@ -313,8 +329,11 @@ type ReactRouterHonoServerPluginOptions = {
##### All adapters
```ts
export type HonoServerOptions<E extends Env = BlankEnv> = {
/**
* Hono app to use
/**
* The base Hono app to use
*
* It will be used to mount the React Router server on the `basename` path
* defined in the [React Router config](https://api.reactrouter.com/v7/types/_react_router_dev.config.Config.html)
*
* {@link Hono}
*/
Expand Down Expand Up @@ -359,13 +378,11 @@ export type HonoServerOptions<E extends Env = BlankEnv> = {
}
) => Promise<AppLoadContext> | AppLoadContext;
/**
* Listening listener (production mode only)
*
* It is called when the server is listening
* Hook to add middleware that runs before any built-in middleware, including assets serving.
*
* Defaults log the port
* You can use it to add protection middleware, for example.
*/
listeningListener?: (info: AddressInfo) => void;
beforeAll?: (app: Hono<E>) => Promise<void> | void;
};
```
Expand Down Expand Up @@ -417,6 +434,19 @@ export async function loader({ context }: Route.LoaderArgs) {
}
```
> [!TIP]
> If you declare your `getLoadContext` function in a separate file, you can use the helper `createGetLoadContext` from `react-router-hono-server/{adapter}`
> ```ts
> import { createGetLoadContext } from "react-router-hono-server/node";
>
> export const getLoadContext = createGetLoadContext((c, { mode, build }) => {
> const isProductionMode = mode === "production";
> return {
> appVersion: isProductionMode ? build.assets.version : "dev",
> };
> });
> ```
##### Node
```ts
export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerOptionsBase<E> {
Expand Down Expand Up @@ -454,12 +484,6 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
* @default false
*/
overrideGlobalObjects?: boolean;
/**
* Hook to add middleware that runs before any built-in middleware, including assets serving.
*
* You can use it to add protection middleware, for example.
*/
beforeAll?: (app: Hono<E>) => Promise<void> | void;
}
```
Expand All @@ -472,18 +496,12 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
* {@link https://bun.sh/docs/api/http#start-a-server-bun-serve}
*/
customBunServer?: Serve & ServeOptions;
/**
* Hook to add middleware that runs before any built-in middleware, including assets serving.
*
* You can use it to add protection middleware, for example.
*/
beforeAll?: (app: Hono<E>) => Promise<void> | void;
}
```
##### Cloudflare Workers
```ts
export interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port" | "beforeAll"> {}
export interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port"> {}
```
## Middleware
Expand Down Expand Up @@ -706,6 +724,55 @@ Cloudflare requires a different approach to WebSockets, based on Durable Objects
>
> Work in progress on Cloudflare team: https://github.com/flarelabs-net/vite-plugin-cloudflare
## Basename and Hono sub apps
> [!NOTE]
> By default, the React Router app is mounted at `/` (default `basename` value).
>
> You may not need to use this option. It's for advanced use cases.
> [!TIP]
> Check this [example](./examples/node/custom-mount/) to see how to use it.
You can use the `basename` option in your React Router config (`react-router.config.ts`) to mount your React Router app on a subpath.
It will automatically mount the app on the subpath.
```ts
// react-router.config.ts
import type { Config } from "@react-router/dev/config";
export default {
basename: "/app", // Now the React Router app will be mounted on /app
} satisfies Config;
```
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.
```ts
import { Hono } from "hono";
import { createHonoServer } from "react-router-hono-server/node";
import { API_BASENAME, api } from "./api";
import { getLoadContext } from "./context";
// Create a root Hono app
const app = new Hono();
// Mount the API app at /api
app.route(API_BASENAME, api);
export default await createHonoServer({
// Pass the root Hono app to the server.
// It will be used to mount the React Router app on the `basename` defined in react-router.config.ts
app,
getLoadContext,
});
```
> [!NOTE]
> You now have two entry points!
> - `/api` - for your API
> - `/app` - for your React Router app
## Pre-rendering
You should be able to use pre-rendering with this package.
Expand Down
Binary file modified bun.lockb
Binary file not shown.
80 changes: 80 additions & 0 deletions examples/bun/custom-mount/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* This is intended to be a basic starting point for linting in your app.
* It relies on recommended configs out of the box for simplicity, but you can
* and should modify this configuration to best suit your team's needs.
*/

/** @type {import('eslint').Linter.Config} */
module.exports = {
root: true,
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
commonjs: true,
es6: true,
},
ignorePatterns: ["!**/.server", "!**/.client"],

// Base config
extends: ["eslint:recommended"],

overrides: [
// React
{
files: ["**/*.{js,jsx,ts,tsx}"],
plugins: ["react", "jsx-a11y"],
extends: [
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
],
settings: {
react: {
version: "detect",
},
formComponents: ["Form"],
linkComponents: [
{ name: "Link", linkAttribute: "to" },
{ name: "NavLink", linkAttribute: "to" },
],
"import/resolver": {
typescript: {},
},
},
},

// Typescript
{
files: ["**/*.{ts,tsx}"],
plugins: ["@typescript-eslint", "import"],
parser: "@typescript-eslint/parser",
settings: {
"import/internal-regex": "^~/",
"import/resolver": {
node: {
extensions: [".ts", ".tsx"],
},
typescript: {
alwaysTryTypes: true,
},
},
},
extends: ["plugin:@typescript-eslint/recommended", "plugin:import/recommended", "plugin:import/typescript"],
},

// Node
{
files: [".eslintrc.cjs"],
env: {
node: true,
},
},
],
};
5 changes: 5 additions & 0 deletions examples/bun/custom-mount/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules

/.cache
/build
.env
36 changes: 36 additions & 0 deletions examples/bun/custom-mount/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Welcome to Remix + Vite!

📖 See the [Remix docs](https://remix.run/docs) and the [Remix Vite docs](https://remix.run/docs/en/main/guides/vite) for details on supported features.

## Development

Run the Vite dev server:

```shellscript
npm run dev
```

## Deployment

First, build your app for production:

```sh
npm run build
```

Then run the app in production mode:

```sh
npm start
```

Now you'll need to pick a host to deploy it to.

### DIY

If you're familiar with deploying Node applications, the built-in Remix app server is production-ready.

Make sure to deploy the output of `npm run build`

- `build/server`
- `build/client`
3 changes: 3 additions & 0 deletions examples/bun/custom-mount/app/components/input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function Input(props: React.ComponentPropsWithoutRef<"input">) {
return <input type="text" placeholder="Input" {...props} />;
}
28 changes: 28 additions & 0 deletions examples/bun/custom-mount/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { LinksFunction } from "react-router";
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";
import styles from "~/styles/tailwind.css?url";

export const links: LinksFunction = () => [{ rel: "stylesheet", href: styles }];

export function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
<link rel="stylesheet" href={styles} />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
}

export default function App() {
return <Outlet />;
}
4 changes: 4 additions & 0 deletions examples/bun/custom-mount/app/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";

export default flatRoutes() satisfies RouteConfig;
60 changes: 60 additions & 0 deletions examples/bun/custom-mount/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useState } from "react";
import { useRevalidator } from "react-router";
import { Input } from "~/components/input";
import { getPublic } from "~/utils/.client/public";
import { getCommon } from "~/utils/.common/common";
import { getSecret } from "~/utils/.server/secret";
import { getEnv } from "~/utils/env.server";
import dbLogo from "/images/database.svg";
import type { Route } from "./+types/_index";

export function loader() {
console.log(getSecret(), getCommon());
return {
env: getEnv(),
};
}

export async function clientLoader({ serverLoader }: Route.ClientLoaderArgs) {
console.log(getPublic(), getCommon());
return {
...(await serverLoader()),
};
}

clientLoader.hydrate = true;

export default function Index({ loaderData: data }: Route.ComponentProps) {
const [value, setValue] = useState("");
console.log("dbLogo", dbLogo);
console.log("value", value);
const { revalidate } = useRevalidator();
return (
<div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center">
<button type="button" onClick={revalidate} className="flex items-center gap-2">
<img src={dbLogo} alt="Database" />
Revalidate
</button>
<input />
<Input value={value} onChange={(e) => setValue(e.target.value)} />
<div className="mt-8 w-full max-w-4xl overflow-x-auto">
<table className="w-full border-collapse bg-gray-100 shadow-md rounded-lg">
<thead>
<tr className="bg-gray-200">
<th className="px-6 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Key</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Value</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{Object.entries(data.env).map(([key, value]) => (
<tr key={key} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{key}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{value ?? "-"}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
Loading

0 comments on commit e048945

Please sign in to comment.