Express

Deploy an Express app

Run your Express API in production with a managed database, logs and environment variables, all from one config file. This guide covers what Express 5 needs in production and deploys it on Modelence.

Last updated /Tested with Express 5.3 and Node.js 22

To deploy an Express app, make it listen on the PORT variable on all interfaces, start it with node rather than a watch tool, and run it on a platform that keeps the process up next to its database. On Modelence you describe the app in modelence.config.json and deploy it with one command. Modelence builds it on an official Node.js image, runs it as containers on AWS in the region you pick out of 17 and creates the MongoDB, PostgreSQL and Redis databases it needs in the same region.

This guide covers what an Express 5 app needs once it runs behind a load balancer: a health route, trust proxy, static files, error handling and a queue worker as a second service. The basics that apply to any Node.js server, such as clean shutdown and TypeScript builds, are in Deploy a Node.js app. If you already have an Express app, skip to Run the app locally.

Express on Modelence at a glance

Start command
node server.js after npm ci, on the official node-22-slim image or any Node.js 18+ image you name
Port
Listens on PORT (3000) on 0.0.0.0, behind a load balancer that sets X-Forwarded-For and X-Forwarded-Proto
Health check
A new container takes traffic only once a route such as /health answers 2xx within 4 seconds
Workers
A queue worker runs as a second service built from the same repository, with no port to listen on
Regions
17 AWS regions, with the app, its databases and their backups in the one you pick
Databases
Managed MongoDB, PostgreSQL and Redis in the app's region over TLS, with production data backed up at least every 6 hours
Logs
Everything the app writes to stdout and stderr shows on the environment's Logs page, with nothing to set up
Price
Free plan to start, and paid plans from $20 a month with the $20 included as usage

Before you start

  • Node.js 18 or newer, which Express 5 needs, and npm
  • A Modelence account, which you can create for free
  • Optionally, Claude Code, Cursor or Codex, if you'd rather have your coding agent write the config and run the deploy

Create an Express app

Create a project and install Express, which installs Express 5:

mkdir my-api && cd my-api
npm init -y
npm install express

Then add server.js. Besides one API route, it has the parts an Express app needs once it runs behind a load balancer, and the production readiness section explains each one:

  • /health is registered first, so no middleware added later can block the health check.
  • trust proxy makes req.ip and req.protocol come from the load balancer's headers.
  • express.static serves public/, and the /{*splat} route sends index.html for any other path, so a single-page frontend can route on the client.
  • In Express 5, an async route that throws or rejects reaches the error handler on its own, with no try and catch or wrapper library.
  • The server reads its port from PORT, falls back to 3000 on your machine and listens on 0.0.0.0. Express 5 passes a listen error, such as a port already in use, to the callback, where the example throws it so the process exits instead of running without a server.

Create public/index.html too, or point express.static at the folder your frontend builds into.

server.js
const path = require('node:path');
const express = require('express');

const app = express();

// Requests reach the app through Modelence's load balancer.
app.set('trust proxy', 1);

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.use(express.json());
app.use(express.static(path.join(__dirname, 'public'), { maxAge: '1h' }));

app.get('/api/items/:id', async (req, res) => {
  const item = await findItem(req.params.id);
  if (!item) {
    return res.status(404).json({ error: 'Item not found' });
  }
  res.json(item);
});

app.use('/api', (req, res) => {
  res.status(404).json({ error: 'Not found' });
});

app.get('/{*splat}', (req, res) => {
  res.sendFile('index.html', { root: path.join(__dirname, 'public') });
});

app.use((err, req, res, next) => {
  const status = err.status ?? 500;
  if (status >= 500) {
    console.error(err);
  }
  res.status(status).json({ error: status >= 500 ? 'Internal server error' : err.message });
});

async function findItem(id) {
  if (!/^\d+$/.test(id)) {
    throw Object.assign(new Error('Invalid item id'), { status: 400 });
  }
  return { id: Number(id), name: `Item ${id}` };
}

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

Run the app locally

Add a start script for production and a dev script that restarts the server when a file changes:

"scripts": {
  "dev": "node --watch server.js",
  "start": "node server.js"
}

Start the development server with npm run dev and open http://localhost:3000/api/items/1.

You can also connect the project to a Modelence local environment, so the app runs on your machine with the environment's database connection strings and variables and they never need to be copied into a .env file. npx modelence@latest setup opens the browser, where you sign in and pick or create an app and environment. After that, start the app with npx modelence@latest dev instead of npm run dev. It runs your dev script with the environment's variables, and the environment's Overview in the dashboard shows the app while it runs.

bash
npx modelence@latest setup
npx modelence@latest dev

Add a database

  • MongoDBMONGODB_URI
  • PostgresDATABASE_URL
  • RedisREDIS_URL

An Express app reaches Modelence's managed MongoDB, PostgreSQL and Redis through connection strings in environment variables. The databases run in the app's region, connections use TLS and production data is backed up at least every six hours.

PostgreSQL and Redis arrive under the names you tie to them in modelence.config.json, usually DATABASE_URL and REDIS_URL, and MongoDB as MONGODB_URI. Create the client in its own module, once per process, and import it in the routes, so every request shares the same pool of connections. With pg for PostgreSQL:

// db.js
const { Pool } = require('pg');

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

module.exports = { pool };

A route can then await the query directly. If the query fails, Express 5 sends the error to the error handler in server.js, so the route needs no try and catch:

const { pool } = require('./db');

app.get('/api/items/:id', async (req, res) => {
  const { rows } = await pool.query('SELECT id, name FROM items WHERE id = $1', [req.params.id]);
  if (rows.length === 0) {
    return res.status(404).json({ error: 'Item not found' });
  }
  res.json(rows[0]);
});

Prisma, Drizzle, Mongoose and the Redis clients work the same way: one client per process, created at startup. A database you keep on Supabase or Neon needs no code changes either, and its URL goes in env with "type": "secret".

Run migrations, whether from Prisma, Knex or your own SQL files, against the environment's database before you deploy rather than in the start command. Every container runs the start command, and a rollout starts several at once.

Declaring a PostgreSQL database or a Redis cache takes a few lines in modelence.config.json, and the deploy creates it before the new version of the API starts:

modelence.config.json
{
  "resources": {
    // "api": the Express service, as in the next 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 builds an Express app as a Node.js service. It runs your build commands on an official Node.js image, here npm ci, then starts the server with node server.js. The file also turns on the HTTP health check, creates the PostgreSQL database and sets NODE_ENV to production, which makes Express cache view templates and keep stack traces out of its default error pages. Add modelence.config.json at the root of the repository and commit it with the app:

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

Adjust the config for your project

  • npm ci installs from package-lock.json. With pnpm, use corepack enable && pnpm install --frozen-lockfile, and with Yarn 2 or newer, corepack enable && yarn install --immutable.
  • If the entry file has another name, such as app.js or bin/www from an older generated app, put that in start. Don't start the app with nodemon or node --watch.
  • For an Express app written in TypeScript, add npm run build to the build commands and start the compiled file, such as node dist/server.js.
  • NODE_ENV reaches only the running app, so npm ci in the build still installs the devDependencies a TypeScript or frontend build needs.
  • Declare keys and tokens with "type": "secret" and no value. The deploy asks you for them in the browser, and you can change them later in the dashboard under Environment variables, where every view of a secret is logged.
  • If a Vite frontend lives in client/, you can let the platform serve it instead of express.static: build it in build and add "static": [{ "path": "/", "dir": "client/dist" }]. Requests that match no file still reach Express.
  • If the app lives in a subdirectory of a monorepo, set root on the service.

Check the build locally

Before the first deploy, run the same commands Modelence will run, in the same order, then check the health route from a second terminal. A deploy runs the same build, so anything that fails here fails there too.

bash
npm ci && PORT=3000 node server.js

# in a second terminal
curl http://localhost:3000/health

Deploy

Run the deploy command in the project directory:

npx modelence@latest deploy

It opens the browser, where you sign in, pick the organization, app and environment (or create them) and enter any required variables the environment doesn't have yet, such as SESSION_SECRET above. Then it uploads the project and follows the build until the app is live. You pick the AWS region the first time you deploy an environment, and its containers and databases are created there. Next time, pass --app <app> --env <env> to preselect the target.

The first deploy creates the database, starts the API once it's ready and attaches the environment's URL, <app>-<environment>.cloud.modelence.app, to the api service. To use your own domain, add it in the dashboard under Domains. Every app has a sandbox and a production environment, and the same file deploys to both.

Let your coding agent do it

Paste Deploy using https://modelence.com/skill.md into Claude Code, Cursor or Codex in your project. The agent reads the docs, writes modelence.config.json for your project, checks the build and runs the deploy, and it stops to ask you whenever a step needs your account.

Production readiness

Check health with a route, not just the port

By default Modelence counts a container as healthy once it accepts connections on its port. With "healthCheck": { "type": "http", "path": "/health" }, the /health route has to answer with a 2xx status within 4 seconds, so a new version that starts but can't serve requests never takes traffic and the deploy rolls back.

Register the route before session, authentication or rate limit middleware, as server.js does, so none of them can answer the check with a 401, 403 or 429. The check arrives with X-Forwarded-Proto: https, so middleware that redirects plain HTTP to HTTPS lets it through. To check the database as well, run a cheap query such as SELECT 1 in the route, and keep it well under the 4 seconds.

Set trust proxy for the load balancer

Requests reach the app through Modelence's load balancer, which terminates HTTPS and passes the client's address and protocol in X-Forwarded-For and X-Forwarded-Proto. Express ignores those headers until you tell it how many proxies to trust:

app.set('trust proxy', 1);

With that, req.ip is the visitor's address, req.protocol is https and req.secure is true. Rate limiters such as express-rate-limit then count each visitor separately instead of treating all traffic as one address, and express-session sets cookies marked secure. Use the number rather than true, which would also trust addresses a client writes into X-Forwarded-For itself, and which express-rate-limit rejects for that reason. If the service also has static mounts, the platform serves them through one more proxy inside the container, so set it to 2.

Serve static files with cache headers

express.static serves files straight from the container, and maxAge sets how long browsers cache them. Files with a content hash in their names, such as a Vite build's assets/, can take a year with immutable: true, while index.html should stay short so a deploy reaches visitors at once.

Express 5 changed the route path syntax, and a bare * now throws Missing parameter name when the server starts. A catch-all route needs a named wildcard, /{*splat}, which also matches /. Register it after the API routes and after a 404 handler for /api, so a mistyped API path gets a JSON 404 rather than the HTML page.

For a frontend built in the same repository, the static key in modelence.config.json is the other option. The platform serves the build output in front of Express with the same fallback to index.html, and Express handles only the requests that match no file.

Handle errors in one place

Express 5 forwards an error thrown or a promise rejected in a route or middleware to the error handler, which is the middleware with four arguments, (err, req, res, next), registered after all routes. Errors that express.json() raises for a malformed body carry status 400, and the handler in server.js passes those messages on while it logs any 5xx and answers with a generic message.

Without a handler of your own, Express's default one prints the stack trace in the response unless NODE_ENV is production, which is why the config sets it. An exception thrown outside the request cycle, for example in a timer, still crashes the process. Modelence then starts a new container, and the error shows on the Logs page.

Keep sessions and state out of the process

express-session keeps sessions in a MemoryStore by default, which lives in one container and is gone after the next deploy, so users get signed out and requests on another container don't see the session. Keep sessions in Redis with connect-redis and a managed Redis cache, keep rate limit counters there too, and send uploads from multer to object storage rather than the container's disk.

Then raise the service to two or more containers under Configure, which keeps the API up through a crash or a zone outage. When a container stops, it gets SIGTERM and 30 seconds before SIGKILL. Deploy a Node.js app shows how to finish open requests in that time.

Run queue jobs in a worker service

Work that shouldn't hold up a response, such as sending email, belongs in a queue that a separate process consumes. With BullMQ and a managed Redis cache, a route adds a job with await emailQueue.add('welcome', { to: req.body.email }), and worker.js processes it:

const { Worker } = require('bullmq');
const IORedis = require('ioredis');

const connection = new IORedis(process.env.REDIS_URL, { maxRetriesPerRequest: null });

const worker = new Worker(
  'emails',
  async (job) => {
    console.log(`Sending welcome email to ${job.data.to}`);
  },
  { connection },
);

process.on('SIGTERM', async () => {
  await worker.close();
  process.exit(0);
});

Add it to modelence.config.json as a second service, next to api, with a Redis cache for the queue:

"worker": {
  "type": "service",
  "image": "node-22-slim",
  "build": { "commands": ["npm ci"] },
  "start": { "commands": ["node worker.js"] },
  "healthCheck": { "type": "none" },
  "rollout": "recreate"
},
"queue": { "type": "redis" }

and "REDIS_URL": { "type": "resource", "resource": "queue", "output": "url" } in env. Both services get every variable, so the API and the worker use the same queue. The worker listens on no port, so it has no health check, and "rollout": "recreate" stops the old worker before the new one starts. Multiple services has the details.

Watch logs and metrics

Logs need no setup. Everything the app writes to stdout and stderr, from console.log to a request logger such as morgan or pino-http, shows on the environment's Logs page. For traces and metrics, add a telemetry resource, tie the standard OpenTelemetry variables to it and start the server with node --require @opentelemetry/auto-instrumentations-node/register server.js, which traces Express routes and database calls without code changes. Deploy setup has the full example.

Modelence vs Vercel, Railway and Render for Express

Vercel, Railway and Render are the platforms people compare most often for deploying an Express app. Railway, Render and Modelence run Express as a long-running server, while Vercel turns the app into a function. The figures below come from each platform's own docs and pricing pages in November 2026.

PlatformHow an Express app runsDatabasesPricing
Modelencenode server.js as long-running containers on AWS in 17 regions, with workers as separate services from the same fileManaged MongoDB, PostgreSQL and Redis, backed up at least every 6 hoursFree plan, then from $20 a month with $20 of usage included
VercelThe whole app as a single Vercel Function on Fluid compute, in 1 region by default, with express.static replaced by the public directoryPostgres, Redis and others through Marketplace providers such as Neon and UpstashHobby is free for personal, non-commercial use; Pro is $20 per developer seat a month with $20 of credit
RailwayRailpack detects Node.js and runs npm start, or Railway builds your Dockerfile, in 4 regionsPostgres, MySQL, Redis and MongoDB templates, with backups you turn onHobby $5 or Pro $20 a month including that much usage, then compute billed by the second
RenderA Node web service in 5 regions, with the build and start commands you setManaged Postgres from $6 a month, Redis-compatible Key Value from $10 a monthWorkspace plan ($0, $25 or $499 a month) plus a fixed price per instance, from $7 a month

Vercel works well for an Express API whose requests are short and stateless, especially when the frontend already lives there, and for teams that preview every pull request. An app that holds WebSocket connections, runs a queue worker or keeps work going after the response fits a platform that runs containers better. Railway is the quickest way from a repository to a running app, and Render's fixed instance prices are easy to budget for steady traffic. Modelence fits when the API, its MongoDB, PostgreSQL or Redis and its workers should run together on AWS in a region you choose, with failed deploys rolled back for you. For more detail, see Modelence vs Vercel and Railway vs Render.

Next steps

Frequently asked questions

How do I deploy an Express app to production?

Make the server listen on the PORT variable on all interfaces, add a health route, set trust proxy and start it with node rather than nodemon or a watch flag. Then run it on a platform that keeps the process up and provides its database. On Modelence you put the build and start commands in modelence.config.json and run npx modelence@latest deploy, and Modelence builds the app on an official Node.js image and runs it as containers in the AWS region you pick.

Can I host an Express app on Vercel?

Yes, Vercel deploys an Express app with zero configuration and runs the whole app as a single Vercel Function on Fluid compute. express.static() doesn't serve files there, so static assets go in the public directory, and the Vercel Functions limits apply to every request. If the app holds WebSocket connections, runs a queue worker or should run as one long-lived Node.js process, a platform that runs containers, such as Modelence, Railway or Render, fits it better.

What changes in Express 5 can break an app on deploy?

The most common one is route paths: Express 5 uses path-to-regexp 8, so a bare * or an unnamed wildcard throws when the server starts, and a catch-all route becomes /{*splat}. Optional parameters use braces, such as /:file{.:ext}, and regular expression characters in string paths are no longer supported. req.body is undefined rather than {} when no body parser ran, res.send(status) now sends the number as the response body instead of setting the status, and removed methods such as req.param() throw. Express 5 also needs Node.js 18 or newer, which every Modelence image provides.

Why does req.ip show the load balancer's address?

Because Express ignores X-Forwarded-For until trust proxy is set, so req.ip is the address of the proxy that opened the connection. On Modelence, add app.set('trust proxy', 1) and req.ip becomes the visitor's address, req.protocol becomes https and secure cookies work. Avoid trust proxy set to true, which also trusts addresses a client sends in the header itself.

Do I need Nginx in front of Express?

No. On Modelence the load balancer terminates HTTPS and spreads requests across containers, and Modelence issues the certificates for your domains, so Express can answer directly on PORT. express.static serves static files well enough for most apps, and for a built frontend the static key in modelence.config.json serves the files in front of Express instead.

How do I run background jobs with Express?

Put the jobs in a queue such as BullMQ on a managed Redis cache and process them in a separate worker service in modelence.config.json, with its own start command such as node worker.js. If the Express server ran them itself, every API container would run every scheduled job, and emails or charges would go out more than once. Give the worker "healthCheck": { "type": "none" } and "rollout": "recreate", since it listens on no port.

Can I deploy an Express API with a React or Vite frontend?

Yes. Build the frontend in the build commands and either serve the output with express.static and a /{*splat} fallback route, or let Modelence serve it with "static": [{ "path": "/", "dir": "client/dist" }] on the same service. Either way the frontend and the API share one domain, so the browser needs no CORS setup. VITE_ variables need "scopes": ["build", "runtime"] because Vite inlines them at build time.

Which database should I use with Express on Modelence?

Any of the three Modelence manages: PostgreSQL with pg, Prisma or Drizzle, MongoDB with the MongoDB driver or Mongoose, or Redis for caching, sessions and queues. Each one runs in the app's region and reaches the app as a connection string in an environment variable. A database you already run on Supabase or Neon works too, with its URL declared as a secret.

How much does it cost to host an Express app on Modelence?

You can start on the free plan, which runs one instance that sleeps when idle. Paid plans start at $20 a month with the same $20 included as cloud usage, and they add managed PostgreSQL and Redis and more than one service, such as a queue worker. Containers are billed hourly by size, from about $9 a month for the smallest one with 0.25 vCPU and 0.5 GB of memory, and the plan price covers the whole team with no charge per seat.

Deploy other stacks

Deploy your Express app

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

Or paste this into your coding agent