React Router

Deploy a React Router v7 app

Run a React Router v7 app in framework mode with server rendering, loaders that read from a managed database and secrets set per environment. This guide takes a new app from create-react-router to a production deploy on Modelence.

Last updated /Tested with React Router 7.18, Vite 8.4 and Node.js 22

To deploy a React Router v7 app on Modelence, add a modelence.config.json file that builds it with react-router build and starts it with react-router-serve ./build/server/index.js, then run npx modelence@latest deploy. Modelence is a managed cloud on AWS that runs the app as a long-running server in one of 17 regions, next to managed MongoDB, Postgres and Redis databases, and takes care of rollouts and backups.

This guide covers framework mode with server rendering, which is what a new React Router app uses by default. It builds a small app whose loader reads from Postgres, deploys it, and then goes through what to change before real traffic arrives. The same steps work for React Router 8 and for a Remix app that has moved to React Router 7. If you already have an app, skip to Run the app locally. For a plain Node.js server see the Node.js or Express guide, and for a React app built on Next.js see Next.js.

React Router on Modelence at a glance

How it runs
react-router-serve runs the server bundle from react-router build in a long-lived container, listening on the PORT Modelence provides
Server code
Loaders, actions and .server modules run only in the container, so connection strings never reach the browser bundle
Regions
17 regions on AWS, with the app's containers and its databases in the same region
Databases
Managed MongoDB, Postgres and Redis next to the app, with production backups at least every six hours
Deploys
The new version starts beside the old one and takes traffic once its health check passes; a crashing version rolls back
SPA mode
With ssr: false, build/client is served as static files with an index.html fallback and no server process
Price
A free plan, and paid plans that start at $20 a month and count that $20 toward usage

Before you start

  • Node.js 20.19 or newer, which Vite 8 needs, and npm
  • A Modelence account, which you can create for free
  • Optionally, Claude Code, Cursor or Codex, if you want your coding agent to write the config and run the deploy

Create a React Router app

create-react-router sets up framework mode with server rendering turned on (ssr: true in react-router.config.ts). Its package.json has a dev script that runs react-router dev, a build script that runs react-router build, and a start script that runs react-router-serve ./build/server/index.js. Without --react-router-version 7, the command now creates a React Router 8 app from the same template, and the rest of this guide works for it unchanged.

bash
npx create-react-router@latest my-app --react-router-version 7
cd my-app
npm install

Read data in a loader

Server code in React Router lives in loaders and actions, and in modules whose name ends in .server. Install a Postgres client with npm install pg and npm install -D @types/pg, then create the connection pool once in app/db.server.ts, so every request in the process shares it:

// app/db.server.ts
import pg from "pg";

// One pool per server process, shared by every request. The .server suffix
// keeps this module and the connection string out of the browser bundle.
export const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });

A route's loader runs on the server before the page renders, and the component gets its result as loaderData. If client code ever imports a .server module, react-router build stops with "Server-only module referenced by client", so the connection string can't end up in the browser by accident. The route file below queries the pool in its loader, and route("items", "routes/items.tsx") in app/routes.ts adds it to the app:

app/routes/items.tsx
import { db } from "../db.server";
import type { Route } from "./+types/items";

// Runs on the server for every request, before the page renders.
export async function loader() {
  const { rows } = await db.query<{ id: number; name: string }>(
    "SELECT id, name FROM items ORDER BY id",
  );
  return { items: rows };
}

export default function Items({ loaderData }: Route.ComponentProps) {
  return (
    <ul>
      {loaderData.items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

Add a health route

A route that exports a loader and no component is a resource route, and React Router sends the loader's Response as it is. Modelence can call it to decide whether a container is ready for traffic, which the config in the deploy step sets up. Add this file:

// app/routes/health.ts
// A resource route: it exports a loader and no component, so it answers with
// the loader's Response instead of rendering a page.
export function loader() {
  return Response.json({ status: "ok" });
}

Then list it in app/routes.ts next to the other routes:

app/routes.ts
import { type RouteConfig, index, route } from "@react-router/dev/routes";

export default [
  index("routes/home.tsx"),
  route("items", "routes/items.tsx"),
  route("health", "routes/health.ts"),
] satisfies RouteConfig;

Run the app locally

Start the development server and open http://localhost:5173:

npm run dev

react-router dev reads a .env file in the project root, so loaders can use DATABASE_URL from there while you work. To skip the .env file, connect the project to a Modelence local environment instead. npx modelence@latest setup opens the browser to sign in and choose or create an app and environment, and npx modelence@latest dev then runs your dev script with that environment's connection strings and variables, while the dashboard shows the running app on the environment's Overview.

bash
npx modelence@latest setup
npx modelence@latest dev

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

Modelence passes the connection strings for its managed MongoDB, Postgres and Redis to the app as environment variables. Production databases are backed up at least every six hours, and connections are encrypted in transit. MongoDB comes in as MONGODB_URI, while Postgres and Redis use whatever names you give them in modelence.config.json, usually DATABASE_URL and REDIS_URL.

In a React Router app, read these variables only where server code runs, which means loaders, actions and .server modules. Vite puts only variables that start with VITE_ into the browser bundle, through import.meta.env, so a connection string without that prefix stays on the server. Open one client per process in a .server module, as app/db.server.ts does above, and hand it to the library you already use, such as pg, Prisma, Drizzle, the MongoDB driver or a Redis client.

A database that already lives at Supabase or Neon keeps working: declare its URL in env with "type": "secret" and enter the value when the deploy asks for it.

Run migrations against the environment's database before you deploy, and keep them out of the start command. Every container runs that command, and a rollout starts more than one, so the same migration would run several times at once.

Declare Postgres and Redis as resources next to the app's service, and the deploy creates them before the new version starts:

modelence.config.json
{
  "resources": {
    // "web": the React Router service from the deploy step
    "main-db": { "type": "postgres", "plan": "postgres-1gb" },
    "cache": { "type": "redis" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "REDIS_URL": { "type": "resource", "resource": "cache", "output": "url" }
  }
}

Describe the app in modelence.config.json

Modelence runs a React Router app as a Node.js service on an official Node.js image. The build commands install the dependencies and run react-router build, which writes the server bundle to build/server and the browser assets to build/client. The start command runs react-router-serve, the Express server that comes with React Router, on that server bundle.

Call react-router-serve from node_modules/.bin rather than through npm start. When a deploy replaces a container, Modelence sends it SIGTERM, and npm exits on that signal right away instead of waiting for the server inside it, which cuts off requests that are still running. SESSION_SECRET is used by the cookie sessions under production readiness below, and the health check calls the /health route from the setup steps. Add the file to the root of the repository and commit it:

modelence.config.json
{
  "$schema": "https://cloud.modelence.com/schema/modelence.config.json?version=1",
  "resources": {
    "web": {
      "type": "service",
      "image": "node-22-slim",
      "build": { "commands": ["npm ci", "npm run build"] },
      "start": { "commands": ["./node_modules/.bin/react-router-serve ./build/server/index.js"] },
      "healthCheck": { "type": "http", "path": "/health" }
    },
    "main-db": { "type": "postgres", "plan": "postgres-1gb" }
  },
  "env": {
    "DATABASE_URL": { "type": "resource", "resource": "main-db", "output": "url" },
    "SESSION_SECRET": { "type": "secret" }
  }
}

Adjust the config for your project

  • npm ci installs exactly what package-lock.json lists. With pnpm or Yarn, run corepack enable first and use that package manager's frozen-lockfile install instead.
  • react-router-serve listens on the PORT Modelence sets and on all interfaces, so it needs no HOST or port flags. Never start the app with react-router dev.
  • Keep node-22-slim unless engines.node in package.json asks for a different Node.js version. React Router 8 needs Node.js 22.22 or newer.
  • Vite writes VITE_ variables into the browser bundle at build time, so give them "scopes": ["build", "runtime"], and never use the prefix for a secret.
  • Declare keys and tokens with "type": "secret" and no value. The deploy asks you for each one, and afterwards you can view or change it in the dashboard under Environment variables, where every view is logged.
  • Set root on the service when the app sits in a folder of a monorepo rather than at the repository root.
  • With ssr: false in react-router.config.ts, the build is a single-page app with no server. Leave out start and healthCheck, and serve the files with "static": [{ "path": "/", "dir": "build/client" }]. Paths that match no file get index.html, so client-side routes still load on a full page refresh.

Check the build locally

Run the commands a deploy runs, in the same order, then open http://localhost:3000/health in another terminal. A build that fails here fails in the cloud too. npx modelence@latest verify goes one step further: it copies the project, runs the build commands from modelence.config.json and starts the app the way a container does, then checks that it answers. It needs no sign-in and lists the variables that the cloud will provide.

bash
npm ci && npm run build && PORT=3000 ./node_modules/.bin/react-router-serve ./build/server/index.js

Deploy

In the project directory, run:

npx modelence@latest deploy

The command opens the browser so you can sign in, choose or create the organization, app and environment, and fill in secrets the environment doesn't have yet, such as SESSION_SECRET. It then uploads the project and streams the build until the new version is live. The first deploy to an environment asks for an AWS region, and the containers and databases for that environment are created there. Later deploys can skip the prompts with --app <app> --env <env>.

On the first deploy, Modelence creates the Postgres database, starts the app once the database is ready and serves the web service at <app>-<environment>.cloud.modelence.app. Add your own domain in the dashboard under Domains. Each app comes with a sandbox and a production environment, and both deploy from the same file.

Let your coding agent do it

In Claude Code, Cursor or Codex, paste Deploy using https://modelence.com/skill.md in the project. The agent reads the docs, writes modelence.config.json for the app, runs the build and the deploy, and asks you whenever a step needs your account.

Production readiness

Finish requests before a container stops

When a deploy replaces a container, Modelence sends SIGTERM and can keep routing new requests to it for about 10 seconds. react-router-serve stops accepting connections the moment it gets SIGTERM and exits once open requests finish, so requests that arrive in those seconds can fail. To keep serving through that window, replace it with a small Express server that uses React Router's Express adapter. Install npm install express compression @react-router/express@7, add server.js at the project root and set the start command to NODE_ENV=production node server.js:

// server.js
import { createRequestHandler } from "@react-router/express";
import compression from "compression";
import express from "express";

const app = express();
app.disable("x-powered-by");
// Read the scheme and host from the load balancer's X-Forwarded-* headers,
// so request.url in loaders and actions starts with https://.
app.set("trust proxy", 1);
app.use(compression());

// Fingerprinted build assets never change, so browsers cache them for a year.
app.use("/assets", express.static("build/client/assets", { immutable: true, maxAge: "1y" }));
app.use(express.static("build/client", { maxAge: "1h" }));

app.use(createRequestHandler({ build: await import("./build/server/index.js") }));

const port = Number(process.env.PORT) || 3000;
const server = app.listen(port, () => console.log(`Listening on port ${port}`));

// Requests can still arrive for about 10 seconds after SIGTERM, so keep
// serving for that long, then finish open requests and exit.
process.once("SIGTERM", () => {
  setTimeout(() => server.close(() => process.exit(0)), 10_000);
});

Modelence waits 30 seconds by default before it stops a container for good, which leaves room for the 10-second delay. If a request can run longer, raise stopTimeout on the service.

Build https URLs behind the load balancer

TLS ends at Modelence's load balancer, which forwards the request over HTTP with X-Forwarded-Proto: https. react-router-serve doesn't read that header, so request.url in loaders and actions starts with http://, and links you build from it, such as an OAuth callback, point at the wrong scheme. The custom server above sets trust proxy, which makes request.url start with https://. With react-router-serve, build absolute links from the SITE_URL variable that Modelence sets for each environment instead.

Keep sessions in a cookie or in Redis

Containers have no persistent disk, and a deploy replaces all of them, so file and in-memory session storage lose every session. A signed cookie session works on any container:

// app/sessions.server.ts
import { createCookieSessionStorage } from "react-router";

if (!process.env.SESSION_SECRET) {
  throw new Error("SESSION_SECRET is not set");
}

// The session lives in a signed cookie, so any container can read it.
export const { getSession, commitSession, destroySession } =
  createCookieSessionStorage<{ userId: string }>({
    cookie: {
      name: "__session",
      httpOnly: true,
      sameSite: "lax",
      secure: process.env.NODE_ENV === "production",
      secrets: [process.env.SESSION_SECRET],
    },
  });

Declare SESSION_SECRET as a secret in modelence.config.json. For sessions that hold more than a cookie can, store them in Redis from the same region. Under Configure in the dashboard, run the service on two or more containers so the app stays up if one crashes or an availability zone goes down.

Expect open tabs to reload after a deploy

Each build gives the browser files new hashed names, and the new containers serve only the new ones. When a tab opened before the deploy navigates to a route whose file is gone, React Router logs the failed import and reloads the page, so the visitor gets the new version after one full page load. Keep forms short-lived or save drafts on the server if a reload in the middle of a form would lose work.

Run background jobs as their own service

Keep queue consumers and scheduled jobs out of the React Router server. With more than one container, each would pick up the same job, and a reminder email would go out once per container. Add a second service to modelence.config.json with its own start command, "healthCheck": { "type": "none" } and "rollout": "recreate", as Multiple services describes.

Watch logs and metrics

react-router-serve prints one line per request, and the environment's Logs page shows that and everything else the app writes to its output, with nothing to set up. For traces and metrics, add a telemetry resource and connect the standard OpenTelemetry variables to it, as the modelence.config.json reference explains.

Modelence vs Vercel, Cloudflare and Railway for React Router

React Router teams most often compare Vercel and Cloudflare, which both maintain their own React Router setup, with Railway, where a community template runs react-router-serve. The table is based on each platform's own docs and pricing pages in November 2026.

PlatformHow a React Router app runsDatabasesPricing
Modelencereact-router-serve or your own Express server in long-running containers on AWS, in 17 regions, across two availability zonesManaged MongoDB, Postgres and Redis in the app's regionFree plan; paid plans from $20 a month with $20 of usage included
VercelServer rendering as Vercel Functions with the Vercel Preset, static files from its CDN; functions run in iad1 by default, with 1 region on Hobby and up to 5 on ProPostgres, Redis and others through Marketplace providers such as Neon, Upstash and SupabaseHobby is $0 with usage caps; Pro is $20 per developer seat a month with $20 of credit, then metered
CloudflareThe Workers runtime on Cloudflare's global network through the Cloudflare Vite plugin, with a subset of Node.js APIsD1 with SQLite semantics, and Hyperdrive for an existing Postgres or MySQL hosted elsewhereFree with 100,000 requests a day; Paid from $5 a month with 10M requests included
RailwayA service that runs your start command, in 4 regions (California, Virginia, Amsterdam, Singapore)Postgres, MySQL, Redis and MongoDB from templatesFree with $1 of usage a month; Hobby $5 or Pro $20 a month, each including that much usage

Cloudflare is the better fit for an app that should render close to visitors all over the world and can work within the Workers runtime and its own storage. Vercel suits a team that wants a zero-config deploy that scales to zero between visits and is happy to rent the database from a Marketplace provider. Railway runs the app as an ordinary Node.js server the way Modelence does, and is a good choice for putting the app and its databases on one canvas with per-second billing. Modelence fits an app whose loaders and actions do real work against a database, running as long-lived containers with that database and its backups in one region you choose. Modelence vs Vercel, Vercel alternatives and Railway alternatives compare the platforms in more depth, and Move from Railway covers a migration.

Next steps

Frequently asked questions

How do I deploy a React Router v7 app?

Build it with react-router build and run the server bundle with react-router-serve ./build/server/index.js on a host that runs Node.js. On Modelence, you describe those two commands in modelence.config.json and run npx modelence@latest deploy, which builds the app, creates any databases it declares and starts it in containers on AWS.

Does a React Router v7 app need a server in production?

Yes, when ssr is true in react-router.config.ts, which is the default, because loaders, actions and server rendering run on every request. With ssr set to false the build is a single-page app of static files, and on Modelence you serve build/client with a static entry and run no server process at all.

Is react-router-serve good enough for production?

Yes for most apps, since it is the Express server React Router ships for production, with compression and long-lived caching for hashed assets. Move to your own Express server with @react-router/express when you need more control, for example to keep serving for a few seconds after SIGTERM, to trust X-Forwarded-Proto, or to add WebSockets.

Can I host a React Router app on AWS without setting up AWS myself?

Yes, because Modelence runs on AWS for you and creates the app's containers, databases and backups without any AWS account setup on your side. You pick one of 17 regions on the first deploy, and the app runs there in containers split across two availability zones, with its databases in the same region.

Why is process.env undefined in my React Router app?

Because process.env exists only in server code, and the browser bundle never gets it. Read variables in loaders, actions and .server modules, and pass what the page needs through loaderData. For a value the browser itself must read, use a VITE_ variable through import.meta.env, which Vite writes into the bundle at build time, so on Modelence it needs the build scope as well as runtime.

How do I connect a React Router app to Postgres?

Create a pg Pool from process.env.DATABASE_URL in a .server module and query it from your loaders and actions. On Modelence, declare a postgres resource in modelence.config.json and tie DATABASE_URL to its url output, and the connection string reaches the container at runtime without ever reaching the browser.

Do these steps work for React Router 8?

Yes. npx create-react-router@latest now creates a React Router 8 app from the same template, with the same build and start scripts, so the config and commands in this guide carry over. React Router 8 needs Node.js 22.22 or newer.

How do I deploy a Remix app that moved to React Router 7?

Deploy it like any React Router 7 app once the upgrade is done. The upgrade replaces @remix-run/serve with @react-router/serve, so the start command changes from remix-serve build/server/index.js to react-router-serve build/server/index.js, and the build command becomes react-router build.

Why do I see "Failed to fetch dynamically imported module" after a deploy?

A tab that was opened before the deploy asked for a JavaScript file from the previous build, which the new containers no longer serve. React Router catches this when it loads a route module and reloads the page once, so the visitor lands on the new version, and the message in the console is expected.

How much does it cost to host a React Router app on Modelence?

It can cost nothing on the free plan, which runs one instance that sleeps when idle. Paid plans begin at $20 a month, all of which counts toward usage, and each container is billed by the hour according to its size, from about $9 a month for the smallest one with 0.25 vCPU and 0.5 GB of memory.

Deploy other stacks

Deploy your React Router app

Start on the free plan and move up when your app needs more.

Or paste this into your coding agent