Repository navigation
How to provide a populated RouteContextProvider from BYO server? #15622
Replies: 4 comments
|
The keys are matched by object identity. The fix is to move the code that builds the context into the Vite build, so only one copy of the keys exists. The official // server/app.ts (compiled into build/server/index.js)
import { RouterContextProvider } from "react-router";
import { resourcesContext, type Resources } from "../app/context";
import { createKoaHandler } from "./koa-adapter"; // whatever wraps createRequestHandler today
export function createReactRouterMiddleware(resources: Resources) {
return createKoaHandler({
build: () => import("virtual:react-router/server-build"),
getLoadContext() {
const context = new RouterContextProvider();
context.set(resourcesContext, resources);
return context;
},
});
}// vite.config.ts
export default defineConfig({
environments: {
ssr: { build: { rollupOptions: { input: "./server/app.ts" } } },
},
plugins: [reactRouter()],
});// server.js (your Koa entry, not bundled)
const resources = await createResources(); // once, at startup
const app = new Koa();
if (process.env.NODE_ENV === "development") {
const vite = await (await import("vite")).createServer({
server: { middlewareMode: true },
appType: "custom",
});
// mount vite.middlewares (connect-style) here
app.use(async (ctx, next) => {
const { createReactRouterMiddleware } = await vite.ssrLoadModule("./server/app.ts");
return createReactRouterMiddleware(resources)(ctx, next);
});
} else {
const { createReactRouterMiddleware } = await import("./build/server/index.js");
app.use(createReactRouterMiddleware(resources));
}In dev, If you'd rather keep the server outside the build, add Two things that won't work on their own:
Tested with react-router, @react-router/dev and @react-router/node 8.4.0, Vite 8.3.4, Koa 3.2.1 and Node 24.18, against the |
|
Building on the object-identity answer above — the practical fix is to make both sides of your server share one module registry, because the duplication isn't in the context API, it's in how the modules get loaded. What's happening: your koa bootstrap loads the module that calls RouterContext() with one loader (Node's require/import), while the app runs through Vite's SSR pipeline. Same file, two module instances, two distinct context objects — so get() on the app side looks up a key that isn't in the Map. Ways out, pick one:
Option 1 is the cleanest — it also fixes any future double-instantiation bugs of the same kind (singletons, class instances, anything identity-sensitive). |
|
This error happens because in a custom BYO server (like Koa or Express) with Vite, your server runtime (the outer Node process) and the SSR bundle ( When you create a Here are the two ways to handle this cleanly: Option 1: Use If you just need to pass server resources (connections, pools, client instances) into your loaders and actions, the standard mechanism in React Router is In your Koa server: // server.ts
import Koa from "koa";
import { createRequestHandler } from "@react-router/node";
import { createFetchRequest, sendFetchResponse } from "./koa-adapter";
// Initialized once at startup
const db = await initDatabasePool();
const redis = await initRedisClient();
const app = new Koa();
function getLoadContext(ctx: Koa.Context) {
return {
db,
redis,
};
}
app.use(async (ctx) => {
const handler = createRequestHandler(
process.env.NODE_ENV === "production"
? await import("./build/server/index.js")
: () => vite.ssrLoadModule("virtual:react-router/server-build")
);
const request = createFetchRequest(ctx.req, ctx.res);
const loadContext = getLoadContext(ctx);
const response = await handler(request, loadContext);
await sendFetchResponse(ctx.res, response);
});To give // app/types.d.ts
import type { DatabasePool } from "./db";
import type { RedisClient } from "./redis";
declare module "react-router" {
interface AppLoadContext {
db: DatabasePool;
redis: RedisClient;
}
}Then consume it in any route: // app/routes/users.tsx
import type { Route } from "./+types/users";
export async function loader({ context }: Route.LoaderArgs) {
// context is typed via AppLoadContext
const users = await context.db.query("SELECT * FROM users");
return { users };
}Option 2: Using If you want or need to use
// app/context.ts
import { createContext, type RouterContext } from "react-router";
import type { Resources } from "./types";
const KEY = Symbol.for("app.resourcesContext");
export const resourcesContext: RouterContext<Resources> =
(globalThis as any)[KEY] ??
((globalThis as any)[KEY] = createContext<Resources>());
// vite.config.ts
import { defineConfig } from "vite";
import { reactRouter } from "@react-router/dev/vite";
export default defineConfig({
plugins: [reactRouter()],
ssr: {
external: ["@my-app/shared-context"], // your shared context package
},
});This ensures Vite delegates importing the module to Node's runtime module cache instead of bundling a duplicate copy, keeping object identity intact across both sides. If this helps/solves your issue, please mark it as the answer so others can find it easily! |
|
If you want to keep the Koa bootstrap and avoid adding a second Vite build entry, export the context factory from your existing // app/entry.server.tsx, alongside the existing default request handler
import { RouterContextProvider } from 'react-router';
import { resourcesContext, type Resources } from './resources.server';
export function makeLoadContext(resources: Resources) {
const context = new RouterContextProvider();
context.set(resourcesContext, resources);
return context;
}Then, where your Koa adapter already loads the server build: const build = await loadServerBuild();
const context = build.entry.module.makeLoadContext(resources);
return createRequestHandler(build)(fetchRequest, context);In dev, use the same loaded virtual server build for the factory and the handler for that request. In production, reuse the imported build and the connections you created at startup, and call the factory once per request. If your adapter types I built a fixture with React Router 8.4.0 and Vite 8.3.5 using Codex. Importing the key separately from Node reproduced the missing-context error. With the entry export, two requests in parallel each returned the resource value supplied to its own provider. Server-build generator |
Uh oh!
There was an error while loading. Please reload this page.
We started with remix and BYO server (koa).
The server code populates the AppLoadContext with various server side resources (client connections and the like) that are expensive to create on startup.
Upgrading from RR7 to RR8, we are running into issues.
All works fine as an RR7 AppLoadContext, but the problem with the RouterContextProvider is the duplicate module loading for the keys (RouterContext). The RouterContextProvider is populated with key loaded by the server module but routes try to get() from RouterContextProvider with key loaded by the app module loader. It always encounters the error “No vale found for context”
How is this meant to work? How are we supposed to pass context from the server to the app?
All reactions