Skip to content

Commit

Permalink
Handle Single fetch redirects (#43)
Browse files Browse the repository at this point in the history
* add beforeAll and overrideGlobalObjects option;
add reactRouterRedirect http helper to handle single fetch redirect;

* disable hono request/response override

* unnecessary server build loading

* fix css build
  • Loading branch information
rphlmr authored Jan 3, 2025
1 parent e943981 commit 170396d
Show file tree
Hide file tree
Showing 38 changed files with 1,168 additions and 506 deletions.
63 changes: 62 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,24 @@ export interface HonoServerOptions<E extends Env = BlankEnv> extends HonoServerO
* For example, you can use this to bind `@hono/node-ws`'s `injectWebSocket`
*/
onServe?: (server: ServerType) => void;
/**
* The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance.
*
* If you want this behavior, set it to `true`
*
* 🚨 Setting this to `true` can break `request.clone()` if you later check `instanceof Request`.
*
* {@link https://github.com/honojs/node-server?tab=readme-ov-file#overrideglobalobjects}
*
* @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 @@ -454,16 +472,34 @@ 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"> {}
export interface HonoServerOptions<E extends Env = BlankEnv> extends Omit<HonoServerOptionsBase<E>, "port" | "beforeAll"> {}
```
## Middleware
🚨 Redirecting from a middleware
> [!IMPORTANT]
> You **have to** use the `reactRouterRedirect` helper to redirect from a middleware.
>
> It returns a single-fetch-like response.
>
> If you use `c.redirect`, it will not work as expected and you will get a `Unable to decode turbo-stream response` error.
>
>```ts
> import { reactRouterRedirect } from "react-router-hono-server/http";
>```
Middleware are functions that are called before React Router calls your loader/action.
Hono is the perfect tool for this, as it supports middleware out of the box.
Expand All @@ -477,6 +513,31 @@ See how [Shelf.nu](https://github.com/Shelf-nu/shelf.nu/blob/main/server/middlew
> [!TIP]
> This lib exports one middleware `cache` (`react-router-hono-server/middleware`) that you can use to cache your responses.
### `beforeAll`
You can use the `beforeAll` option to add middleware that runs before any built-in middleware, including assets serving.
You can use it to add protection middleware, for example.
> [!TIP]
> When you check the path to protect, don't forget to use `c.req.path.includes("")` to handle `.data` requests (`loader`)!
```ts
import { reactRouterRedirect } from "react-router-hono-server/http";
import { createHonoServer } from "react-router-hono-server/node";
export default await createHonoServer({
beforeAll(app) {
app.use(async (c, next) => {
if (c.req.path.includes("/protected") && !c.req.header("Authorization")) {
return reactRouterRedirect("/login");
}
return next();
});
},
});
```
### Using remix-hono middleware
It is easy to use [remix-hono](https://github.com/sergiodxa/remix-hono) middleware with this package.
Expand Down
80 changes: 80 additions & 0 deletions examples/node/protected-routes/.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/node/protected-routes/.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/node/protected-routes/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/node/protected-routes/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} />;
}
12 changes: 12 additions & 0 deletions examples/node/protected-routes/app/entry.client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { StrictMode, startTransition } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<HydratedRouter />
</StrictMode>
);
});
63 changes: 63 additions & 0 deletions examples/node/protected-routes/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { PassThrough } from "node:stream";

import { createReadableStreamFromReadable } from "@react-router/node";
import { isbot } from "isbot";
import type { RenderToPipeableStreamOptions } from "react-dom/server";
import { renderToPipeableStream } from "react-dom/server";
import type { AppLoadContext, EntryContext } from "react-router";
import { ServerRouter } from "react-router";

export const streamTimeout = 5_000;

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
routerContext: EntryContext,
loadContext: AppLoadContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
let userAgent = request.headers.get("user-agent");

// Ensure requests from bots and SPA Mode renders wait for all content to load before responding
// https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation
let readyOption: keyof RenderToPipeableStreamOptions =
(userAgent && isbot(userAgent)) || routerContext.isSpaMode ? "onAllReady" : "onShellReady";

const { pipe, abort } = renderToPipeableStream(<ServerRouter context={routerContext} url={request.url} />, {
[readyOption]() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);

responseHeaders.set("Content-Type", "text/html");

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);

pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
});

// Abort the rendering stream after the `streamTimeout` so it has tine to
// flush down the rejected boundaries
setTimeout(abort, streamTimeout + 1000);
});
}
28 changes: 28 additions & 0 deletions examples/node/protected-routes/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/node/protected-routes/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;
65 changes: 65 additions & 0 deletions examples/node/protected-routes/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { useState } from "react";
import { Link, NavLink, 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)} />
<NavLink to="/protected">You can't see me</NavLink>
<figure>
<img src="/protected/secret.jpeg" alt="Secret image" />
<figcaption>To see this image, comment the "beforeAll" option in server.ts</figcaption>
</figure>
<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 170396d

Please sign in to comment.