NestJS

Deploy a NestJS app

Run your NestJS backend in production with PostgreSQL or Redis created on the first deploy, plus logs and environment variables from one config file. This guide covers the build, ConfigModule, TypeORM and migrations.

Last updated /Tested with NestJS 12.6, TypeORM 1.1 and Node.js 22

To deploy a NestJS app, compile it to dist with nest build, start the compiled main.js with node and give it its configuration and database through environment variables. 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 on the first deploy.

This guide takes a new NestJS 12 project to production: a health check with Terminus, configuration that ConfigModule validates at startup, a TypeORM connection to a managed PostgreSQL database with migrations, and a BullMQ processor as a second service. If you already have a NestJS app, skip to Run the app locally.

NestJS on Modelence at a glance

Start command
node dist/main.js after npm ci and npm run build, on the official node-22-slim image
Node.js version
NestJS 12 needs Node.js 20.19 or 22.12 or newer, which the node-22-slim image and newer ones provide
Health check
A new container takes traffic only once /health answers 2xx within 4 seconds, which Terminus covers
Configuration
Environment variables from modelence.config.json reach ConfigService, and secrets are set in the browser
Workers
BullMQ processors run 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
Price
Free plan to start, and paid plans from $20 a month with the $20 included as usage

Before you start

  • Node.js 20.19 or 22.12 or newer, which NestJS 12 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 a NestJS project

Create a project with the Nest CLI:

npx @nestjs/cli@latest new my-api --package-manager npm
cd my-api

NestJS 12 projects are TypeScript compiled to ES modules, so npm run build runs nest build and writes JavaScript to dist, and the server starts from dist/main.js. If npm install fails with npm 10 while the CLI creates the project, run npx npm@11 install in the new directory once, and npm ci works with either version after that.

Then change src/main.ts so the app can run behind a load balancer. The production readiness section explains each change:

  • The app listens on the port in PORT and on 0.0.0.0, so the platform can reach it inside the container. It falls back to 3000 on your machine.
  • trust proxy makes req.ip and req.protocol come from the load balancer's headers. NestExpressApplication gives app.set its type, since NestJS runs on Express by default.
  • enableShutdownHooks lets the app react to SIGTERM, so a container that's being replaced finishes its requests and closes the database connection before it exits.
src/main.ts
import { NestFactory } from '@nestjs/core';
import type { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule, ObserveInstrument } from './app.module.js';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    instrument: ObserveInstrument,
  });
  app.set('trust proxy', 1);
  app.enableShutdownHooks();
  await app.listen(process.env.PORT ?? 3000, '0.0.0.0');
}
await bootstrap();

Validate configuration with ConfigModule

Install @nestjs/config, along with Zod for the schema:

npm install @nestjs/config zod

Register ConfigModule globally in src/app.module.ts with a validationSchema. NestJS 12 accepts any Standard Schema library there, such as Zod or Valibot:

import { ConfigModule } from '@nestjs/config';
import { z } from 'zod';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      validationSchema: z.object({
        DATABASE_URL: z.url(),
        PORT: z.coerce.number().default(3000),
      }),
    }),
    // ...
  ],
})
export class AppModule {}

If a variable is missing or malformed, the app stops at startup with Config validation error and the name of the variable. On Modelence that line shows on the Logs page, and since the new version never passes its health check, the deploy rolls back and the running version keeps serving.

Locally, ConfigModule reads a .env file as well. When a variable exists both in the environment and in .env, the environment wins, so the values from modelence.config.json are the ones the deployed app uses. Read them in providers with config.getOrThrow('DATABASE_URL'), which fails loudly instead of handing you undefined.

The new project also sets up @nestjs/observe, which sends traces only once OBSERVE_APP_KEY and OBSERVE_APP_SECRET are set. If you use it, declare both as secrets in modelence.config.json.

Run the app locally

Start the development server, which rebuilds and restarts on every change:

npm run start:dev

Then open http://localhost:3000/health.

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, which runs the dev commands from modelence.config.json, here npm run start:dev, with the environment's variables. 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

A NestJS 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.

With TypeORM, install @nestjs/typeorm, typeorm and pg, then register the connection with forRootAsync, so it reads the URL from ConfigService once ConfigModule has validated it:

TypeOrmModule.forRootAsync({
  inject: [ConfigService],
  useFactory: (config: ConfigService) => ({
    type: 'postgres',
    url: config.getOrThrow<string>('DATABASE_URL'),
    autoLoadEntities: true,
    synchronize: false,
  }),
}),

Keep synchronize off. With it on, every container that starts alters the tables to match the entities, and a rollout starts several containers at once. Change the schema with migrations instead. The TypeORM CLI needs a data source of its own, outside the Nest modules:

// src/data-source.ts
import { DataSource } from 'typeorm';
import { Item } from './items/item.entity.js';

export default new DataSource({
  type: 'postgres',
  url: process.env.DATABASE_URL,
  entities: [Item],
  migrations: ['dist/migrations/*.js'],
});

Generate a migration from the entities and run it against the environment's database before you deploy the code that needs it, rather than in the start command:

npm run build
npx typeorm migration:generate src/migrations/CreateItems -d dist/data-source.js
npm run build
npx typeorm migration:run -d dist/data-source.js

With Prisma, add npx prisma generate to the build commands before npm run build and run npx prisma migrate deploy before you deploy. For MongoDB, @nestjs/mongoose takes MONGODB_URI the same way through forRootAsync. A database you keep on Supabase or Neon needs no code changes either, and its URL goes in env with "type": "secret".

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 NestJS 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 a NestJS app as a Node.js service. It runs your build commands on an official Node.js image, here npm ci and npm run build, then starts the compiled app with node dist/main.js, which is what npm run start:prod runs. The file also turns on the HTTP health check, creates the PostgreSQL database and ties its URL to DATABASE_URL. 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", "npm run build"] },
      "start": { "commands": ["node dist/main.js"] },
      "dev": { "commands": ["npm run start:dev"] },
      "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" }
  }
}

Adjust the config for your project

  • npm ci installs devDependencies too, which nest build needs. NODE_ENV reaches only the running app, so it doesn't change what the build installs.
  • With pnpm, use corepack enable && pnpm install --frozen-lockfile and pnpm build, and with Yarn 2 or newer, corepack enable && yarn install --immutable and yarn build.
  • With Prisma, add npx prisma generate before npm run build.
  • In a Nest monorepo, build one app with npx nest build api and start node dist/apps/api/main.js.
  • 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 the app lives in a subdirectory of a repository, 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. The app validates DATABASE_URL at startup, so point it at a local database or at the sandbox environment's database. A deploy runs the same build, so anything that fails here fails there too.

bash
npm ci && npm run build
DATABASE_URL=postgres://localhost:5432/my_api PORT=3000 node dist/main.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. 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 PostgreSQL database, starts the API once it's ready and attaches the environment's URL, <app>-<environment>.cloud.modelence.app, to the api service. Run your migrations against the new database, then open /health. 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

Add a health check with Terminus

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

@Controller('health')
export class HealthController {
  constructor(
    private readonly health: HealthCheckService,
    private readonly db: TypeOrmHealthIndicator,
  ) {}

  @Get()
  @HealthCheck()
  check() {
    return this.health.check([() => this.db.pingCheck('database').withTimeout('1s')]);
  }
}

Import TerminusModule.forRoot({ gracefulShutdownTimeoutMs: 10_000 }) in the module that declares the controller. Together with enableShutdownHooks, a container that gets SIGTERM answers /health with 503 and keeps serving other requests for 10 seconds, which covers the requests that still reach it during a rollout, then closes its connections and exits. Keep guards such as authentication or rate limits off this controller.

Start the compiled app with node

Start node dist/main.js, the same thing npm run start:prod runs, rather than nest start. nest start compiles the TypeScript every time the process starts and needs the Nest CLI from devDependencies, so containers take longer to become healthy. With node there is a single process, and it receives SIGTERM directly when a container stops. A container gets 30 seconds between SIGTERM and SIGKILL, which leaves room for the 10 second drain above.

Run migrations before the deploy

Run migration:run or prisma migrate deploy against the environment's database before you deploy code that depends on the change, and keep migrations backward compatible, since the old and new versions run side by side for a short time during a rollout. Running migrations in the start command makes every container try them at once, and setting migrationsRun: true in TypeORM has the same effect.

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. On the Express platform, app.set('trust proxy', 1) in main.ts makes req.ip the visitor's address and req.protocol https, so @nestjs/throttler counts each visitor separately and secure cookies work. Use the number rather than true, which would also trust addresses a client writes into the header itself. On Fastify, pass new FastifyAdapter({ trustProxy: 1 }) instead.

Run BullMQ processors in a worker service

Jobs such as sending email belong in a queue that a separate process consumes. With @nestjs/bullmq and a managed Redis cache, register the connection from REDIS_URL:

BullModule.forRootAsync({
  inject: [ConfigService],
  useFactory: (config: ConfigService) => ({
    connection: new Redis(config.getOrThrow<string>('REDIS_URL'), { maxRetriesPerRequest: null }),
  }),
}),
BullModule.registerQueue({ name: 'emails' }),

The API adds jobs with an injected Queue, and src/worker.ts starts a module that holds only the processors, with no HTTP server:

const app = await NestFactory.createApplicationContext(WorkerModule);
app.enableShutdownHooks();

Add it to modelence.config.json as a second service, next to api:

"worker": {
  "type": "service",
  "image": "node-22-slim",
  "build": { "commands": ["npm ci", "npm run build"] },
  "start": { "commands": ["node dist/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 they share the 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.

Keep state out of the process

A container has no persistent disk and is replaced on every deploy, so keep cache entries from @nestjs/cache-manager, rate limit counters and sessions in Redis rather than in memory, and send uploads to object storage. Then raise the service to two or more containers under Configure, which keeps the API up through a crash or a zone outage. Cron jobs from @nestjs/schedule run in every container, so move them to the worker service and keep it at one container.

Watch logs and traces

Logs need no setup. Everything the Nest Logger writes to stdout and stderr shows on the environment's Logs page. For one JSON object per line, which is easier to search, create the app with logger: new ConsoleLogger({ json: true }). For traces and metrics, use @nestjs/observe, or add a telemetry resource and the OpenTelemetry Node.js SDK. Deploy setup has the full example.

Modelence vs Vercel, Railway and Render for NestJS

Vercel, Railway and Render are the platforms people compare most often for NestJS deployment. Railway, Render and Modelence run NestJS 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 a NestJS app runsDatabasesPricing
Modelencenode dist/main.js as long-running containers on AWS in 17 regions, with BullMQ 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 defaultPostgres, 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 the build and start scripts, 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 suits a NestJS API whose requests are short and stateless, and teams that preview every pull request. Queue processors, cron jobs, WebSocket gateways and microservice transports expect a process that keeps running, which 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 a NestJS app to production?

Build it with nest build, start dist/main.js with node, listen on the PORT variable on 0.0.0.0 and give it its database and secrets through environment variables. Then run it on a platform that keeps the process up and provides the database. On Modelence you put npm ci, npm run build and node dist/main.js in modelence.config.json and run npx modelence@latest deploy, and the first deploy also creates the PostgreSQL or Redis the config declares.

Should I use nest start or node dist/main in production?

Use node dist/main.js, which is what the start:prod script runs. nest start compiles the project every time it starts and needs the Nest CLI from devDependencies, so it belongs in development. Build once in the build step and start the compiled output.

Can I deploy NestJS on Vercel?

Yes, Vercel deploys a NestJS app with zero configuration and runs the whole app as a single Vercel Function on Fluid compute, so the Vercel Functions limits apply to every request. BullMQ processors, @nestjs/schedule cron jobs, WebSocket gateways and microservice transports expect a process that keeps running, so an app that uses them fits a platform that runs containers, such as Modelence, Railway or Render.

How do I run TypeORM migrations when I deploy NestJS?

Keep synchronize set to false, generate migrations with the TypeORM CLI and a separate data-source file, and run npx typeorm migration:run -d dist/data-source.js against the environment's database before you deploy the code that needs the change. Avoid running them in the start command or with migrationsRun, because every container would try them at once during a rollout.

How do I use Prisma with NestJS on Modelence?

Add npx prisma generate to the build commands before npm run build, since the generated client isn't in the repository, and run npx prisma migrate deploy against the environment's database before you deploy. Prisma 7 reads the connection string through a driver adapter such as @prisma/adapter-pg, which takes DATABASE_URL from ConfigService.

Why does my NestJS app fail with a config validation error after deploy?

ConfigModule checks the environment against your validationSchema at startup, and the deployed environment is missing a variable that your local .env file has. Add it to env in modelence.config.json, as a resource output for database URLs or as a secret for keys, and deploy again. The failed version never passes its health check, so the previous one keeps serving in the meantime.

How do I run BullMQ queues with NestJS in production?

Register @nestjs/bullmq with an ioredis connection from REDIS_URL, add jobs from the API and run the processors in a worker started with NestFactory.createApplicationContext, as a second service in modelence.config.json with node dist/worker.js as its start command. Give the worker "healthCheck": { "type": "none" } and "rollout": "recreate", since it listens on no port.

Which database should I use with NestJS on Modelence?

Any of the three Modelence manages: PostgreSQL with TypeORM, Prisma or MikroORM, MongoDB with @nestjs/mongoose, or Redis for caching, queues and rate limits. Each one runs in the app's region and reaches the app as a connection string in an environment variable that ConfigService reads. 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 a NestJS 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 BullMQ 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 NestJS app

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

Or paste this into your coding agent