From 75386b89ca4ce2dbfad690d951074f2bb1eacdc3 Mon Sep 17 00:00:00 2001 From: Brooks Lybrand Date: Wed, 25 Jun 2025 09:56:54 -0500 Subject: [PATCH 1/3] docs: Add "Server Bundles" and "Presets" docs (#13879) * docs: server-bundles.md * docs: preset.md * docs: improve clarity and consistency in presets and server-bundles documentation --- docs/how-to/presets.md | 102 ++++++++++++++++++++++++++++++++++ docs/how-to/server-bundles.md | 65 ++++++++++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 docs/how-to/presets.md create mode 100644 docs/how-to/server-bundles.md diff --git a/docs/how-to/presets.md b/docs/how-to/presets.md new file mode 100644 index 0000000000..13e3058f38 --- /dev/null +++ b/docs/how-to/presets.md @@ -0,0 +1,102 @@ +--- +title: Presets +--- + +# Presets + +[MODES: framework] + +## Overview + +The [React Router config][react-router-config] supports a `presets` option to ease integration with other tools and hosting providers. + +[Presets][preset-type] can only do two things: + +- Configure React Router config options on your behalf +- Validate the resolved config + +The config returned by each preset is merged in the order the presets were defined. Any config directly specified in your React Router config will be merged last. This means that your config will always take precedence over any presets. + +## Defining preset config + +As a basic example, let's create a preset that configures a [server bundles function][server-bundles]: + +```ts filename=my-cool-preset.ts +import type { Preset } from "@react-router/dev/config"; + +export function myCoolPreset(): Preset { + return { + name: "my-cool-preset", + reactRouterConfig: () => ({ + serverBundles: ({ branch }) => { + const isAuthenticatedRoute = branch.some((route) => + route.id.split("/").includes("_authenticated") + ); + + return isAuthenticatedRoute + ? "authenticated" + : "unauthenticated"; + }, + }), + }; +} +``` + +## Validating config + +Keep in mind that other presets and user config can still override the values returned from your preset. + +In our example preset, the `serverBundles` function could be overridden with a different, conflicting implementation. If we want to validate that the final resolved config contains the `serverBundles` function from our preset, we can use the `reactRouterConfigResolved` hook: + +```ts filename=my-cool-preset.ts lines=[22-27] +import type { + Preset, + ServerBundlesFunction, +} from "@react-router/dev/config"; + +const serverBundles: ServerBundlesFunction = ({ + branch, +}) => { + const isAuthenticatedRoute = branch.some((route) => + route.id.split("/").includes("_authenticated") + ); + + return isAuthenticatedRoute + ? "authenticated" + : "unauthenticated"; +}; + +export function myCoolPreset(): Preset { + return { + name: "my-cool-preset", + reactRouterConfig: () => ({ serverBundles }), + reactRouterConfigResolved: ({ reactRouterConfig }) => { + if ( + reactRouterConfig.serverBundles !== serverBundles + ) { + throw new Error("`serverBundles` was overridden!"); + } + }, + }; +} +``` + +The `reactRouterConfigResolved` hook should only be used when it would be an error to merge or override your preset's config. + +## Using a preset + +Presets are designed to be published to npm and used within your React Router config. + +```ts filename=react-router.config.ts lines=[6] +import type { Config } from "@react-router/dev/config"; +import { myCoolPreset } from "react-router-preset-cool"; + +export default { + // ... + presets: [myCoolPreset()], +} satisfies Config; +``` + +[react-router-config]: https://api.reactrouter.com/v7/types/_react_router_dev.config.Config.html +[preset-type]: https://api.reactrouter.com/v7/types/_react_router_dev.config.Preset.html +[server-bundles]: ./server-bundles diff --git a/docs/how-to/server-bundles.md b/docs/how-to/server-bundles.md new file mode 100644 index 0000000000..459ce19124 --- /dev/null +++ b/docs/how-to/server-bundles.md @@ -0,0 +1,65 @@ +--- +title: Server Bundles +--- + +# Server Bundles + +[MODES: framework] + +## Overview + +This is an advanced feature designed for hosting provider integrations. When compiling your app into multiple server bundles, there will need to be a custom routing layer in front of your app directing requests to the correct bundle. + +React Router typically builds your server code into a single bundle that exports a request handler function. However, there are scenarios where you might want to split your route tree into multiple server bundles, each exposing a request handler function for a subset of routes. To provide this flexibility, [`react-router.config.ts`][react-router-config] supports a `serverBundles` option, which is a function for assigning routes to different server bundles. + +The [`serverBundles` function][server-bundles-function] is called for each route in the tree (except for routes that aren't addressable, e.g., pathless layout routes) and returns a server bundle ID that you'd like to assign that route to. These bundle IDs will be used as directory names in your server build directory. + +For each route, this function receives an array of routes leading to and including that route, referred to as the route `branch`. This allows you to create server bundles for different portions of the route tree. For example, you could use this to create a separate server bundle containing all routes within a particular layout route: + +```ts filename=react-router.config.ts lines=[5-13] +import type { Config } from "@react-router/dev/config"; + +export default { + // ... + serverBundles: ({ branch }) => { + const isAuthenticatedRoute = branch.some((route) => + route.id.split("/").includes("_authenticated") + ); + + return isAuthenticatedRoute + ? "authenticated" + : "unauthenticated"; + }, +} satisfies Config; +``` + +Each `route` in the `branch` array contains the following properties: + +- `id` — The unique ID for this route, named like its `file` but relative to the app directory and without the extension, e.g., `app/routes/gists.$username.tsx` will have an `id` of `routes/gists.$username` +- `path` — The path this route uses to match the URL pathname +- `file` — The absolute path to the entry point for this route +- `index` — Whether this route is an index route + +## Build manifest + +When the build is complete, React Router will call the `buildEnd` hook, passing a `buildManifest` object. This is useful if you need to inspect the build manifest to determine how to route requests to the correct server bundle. + +```ts filename=react-router.config.ts lines=[5-7] +import type { Config } from "@react-router/dev/config"; + +export default { + // ... + buildEnd: async ({ buildManifest }) => { + // ... + }, +} satisfies Config; +``` + +When using server bundles, the build manifest contains the following properties: + +- `serverBundles` — An object that maps bundle IDs to the bundle's `id` and `file` +- `routeIdToServerBundleId` — An object that maps route IDs to their server bundle ID +- `routes` — A route manifest that maps route IDs to route metadata. This can be used to drive a custom routing layer in front of your React Router request handlers + +[react-router-config]: https://api.reactrouter.com/v7/types/_react_router_dev.config.Config.html +[server-bundles-function]: https://api.reactrouter.com/v7/types/_react_router_dev.config.ServerBundlesFunction.html From a3c73995d7eb4a355ec253d1452b2671e20b7a71 Mon Sep 17 00:00:00 2001 From: Yuri Poliantsev Date: Wed, 25 Jun 2025 18:19:41 +0300 Subject: [PATCH 2/3] docs: add Backend for Frontend docs (#13794) * docs: add bff from Remix docs * Update docs/how-to/backend-for-frontend.md * docs: move bff doc to explanations --------- Co-authored-by: Brooks Lybrand --- contributors.yml | 1 + docs/explanation/backend-for-frontend.md | 45 ++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 docs/explanation/backend-for-frontend.md diff --git a/contributors.yml b/contributors.yml index 8cbb9ba517..649e5ca2ac 100644 --- a/contributors.yml +++ b/contributors.yml @@ -399,6 +399,7 @@ - yracnet - ytori - yuleicul +- yuri-poliantsev - zeevick10 - zeromask1337 - zheng-chuang diff --git a/docs/explanation/backend-for-frontend.md b/docs/explanation/backend-for-frontend.md new file mode 100644 index 0000000000..53c53ce88c --- /dev/null +++ b/docs/explanation/backend-for-frontend.md @@ -0,0 +1,45 @@ +--- +title: Backend For Frontend +--- + +# Backend For Frontend + +While React Router can serve as your fullstack application, it also fits perfectly into the "Backend for Frontend" architecture. + +The BFF strategy employs a web server with a job scoped to serving the frontend web app and connecting it to the services it needs: your database, mailer, job queues, existing backend APIs (REST, GraphQL), etc. Instead of your UI integrating directly from the browser to these services, it connects to the BFF, and the BFF connects to your services. + +Mature apps already have a lot of backend application code in Ruby, Elixir, PHP, etc., and there's no reason to justify migrating it all to a server-side JavaScript runtime just to get the benefits of React Router. Instead, you can use your React Router app as a backend for your frontend. + +You can use `fetch` right from your loaders and actions to your backend. + +```tsx lines=[7,13,17] +import escapeHtml from "escape-html"; + +export async function loader() { + const apiUrl = "https://api.example.com/some-data.json"; + const res = await fetch(apiUrl, { + headers: { + Authorization: `Bearer ${process.env.API_TOKEN}`, + }, + }); + + const data = await res.json(); + + const prunedData = data.map((record) => { + return { + id: record.id, + title: record.title, + formattedBody: escapeHtml(record.content), + }; + }); + return { prunedData }; +} +``` + +There are several benefits of this approach vs. fetching directly from the browser. The highlighted lines above show how you can: + +1. Simplify third-party integrations and keep tokens and secrets out of client bundles +2. Prune the data down to send less kB over the network, speeding up your app significantly +3. Move a lot of code from browser bundles to the server, like `escapeHtml`, which speeds up your app. Additionally, moving code to the server usually makes your code easier to maintain since server-side code doesn't have to worry about UI states for async operations + +Again, React Router can be used as your only server by talking directly to the database and other services with server-side JavaScript APIs, but it also works perfectly as a backend for your frontend. Go ahead and keep your existing API server for application logic and let React Router connect the UI to it. From d48142806fa606c1f9c6f0052366712e96dbe8b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20De=20Boey?= Date: Wed, 25 Jun 2025 17:27:25 +0200 Subject: [PATCH 3/3] docs(tutorials/quickstart): fix grammar + remove duplicate link (#13881) --- docs/tutorials/quickstart.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/tutorials/quickstart.md b/docs/tutorials/quickstart.md index 36e953d6e5..1305e5eb58 100644 --- a/docs/tutorials/quickstart.md +++ b/docs/tutorials/quickstart.md @@ -94,7 +94,7 @@ touch app/routes.js export default []; ``` -The existence of `routes.js` is required to build a React Router app; if you're using React Router we assume you'll want to do some routing eventually. You can read more about defining routes in our [Routing][routing] guide. +The existence of `routes.js` is required to build a React Router app; if you're using React Router, we assume you'll want to do some routing eventually. You can read more about defining routes in our [Routing][routing] guide. ## Build and Run @@ -292,7 +292,6 @@ What's next? [inspect]: https://nodejs.org/en/docs/guides/debugging-getting-started/ [vite-config]: https://vite.dev/config [routing]: ../start/framework/routing -[templates]: /resources?category=templates [http-localhost-3000]: http://localhost:3000 [vite]: https://vitejs.dev [react-router-config]: https://api.reactrouter.com/v7/types/_react_router_dev.config.Config.html