# Deploy NestJS 12 with PostgreSQL: ESM, start:prod and migrations before traffic

Gregale · Updated 2026-11-30

Start compiled NestJS 12, move to ESM, use node-postgres behind a pooler and run migrations with their own credential. Measured on Gregale.

**To deploy a NestJS app, build it once and start the compiled output; to
add PostgreSQL, run migrations as a separate step with their own
credential.** NestJS 12 adds one wrinkle: it is ESM-only, so a project
started from an older template needs a few changes before it compiles.
This page walks through a NestJS 12 API with PostgreSQL on Gregale. Our
test API deployed in 81 seconds and, once parked, was restored in 66 to 74
ms.

_Gregale publishes this page. The numbers are from our own test on November
30, 2026, described below._

## Start the compiled app, not the dev server

`nest start --watch` and `ts-node` compile on every start. In production
that slows each cold start and keeps the compiler in memory. Build once,
then run the output:

```json
{
  "scripts": {
    "build": "nest build",
    "start": "nest start",
    "start:prod": "node dist/main"
  }
}
```

Gregale runs `npm run build`, then starts `npm run start:prod` when the
script exists, otherwise `npm run start`. A `start` script that runs a
development server gets a `development_start_command` warning. You can also
name the command in `gregale.yaml`:

```yaml
hosting:
  start: node dist/main.js
  health: /healthz
```

Listen on the port the platform gives you, on every interface:

```ts
await app.listen(process.env.PORT ?? 3000, '0.0.0.0');
```

## NestJS 12 is ESM-only

`@nestjs/core` 12 is published as an ES module. A project that imports it
needs to be one too:

- `"type": "module"` in `package.json`;
- `"module": "nodenext"` and `"moduleResolution": "nodenext"` in
  `tsconfig.json`, with `experimentalDecorators` and `emitDecoratorMetadata`
  still on, because Nest's dependency injection reads the emitted types;
- a `.js` extension on every relative import, even in `.ts` files:
  `import { AppModule } from './app.module.js'`.

Top-level `await` then works in `main.ts`, so `bootstrap()` can go. `tsc`
builds the project without the Nest CLI, which keeps the development
dependencies small.

## Keep the deployed app small

TypeScript and the Nest CLI are needed to build, not to run. When the deploy
ships `node_modules`, drop them at the end of the build:

```json
{
  "scripts": {
    "build": "tsc -p tsconfig.build.json && node scripts/prune-dev-deps.js"
  }
}
```

The script runs `npm prune --omit=dev` only when there is no `.git`
directory, so a local build keeps your tools. Our API's app layer was 92 MB
after the prune; Gregale's limits are 256 MB on Free and 512 MB on Hobby.

## PostgreSQL through a pooler

A serverless app opens connections in bursts, so managed Postgres usually
puts a connection pooler in transaction mode in front of the database. Two
things follow:

- **No session state across transactions.** node-postgres (`pg`) sends
  unnamed statements, which work as they are. A client that names prepared
  statements needs them turned off.
- **Close idle connections.** Set `idleTimeoutMillis` on the pool, so the
  database can suspend when the app is idle, and close the pool on shutdown:

```ts
@Injectable()
export class Db implements OnModuleDestroy {
  readonly pool = new pg.Pool({
    connectionString: process.env.DATABASE_URL,
    max: 5,
    idleTimeoutMillis: 30_000,
  });

  async onModuleDestroy() {
    await this.pool.end();
  }
}
```

`app.enableShutdownHooks()` in `main.ts` makes Nest call `onModuleDestroy`
when the platform stops an instance.

node-postgres 8 prints a security warning when the URL says
`sslmode=require`, because it already verifies the certificate as
`verify-full` would. Rewriting the parameter to `sslmode=verify-full` keeps
the same check and removes the warning.

## Migrations before traffic, with their own credential

Don't run migrations when the app starts: with several instances starting at
once, they race, and the serving credential shouldn't be able to change the
schema. Run them as a release command, which runs once before a new version
takes traffic. On Gregale, `gregale.yaml` creates the database and gives only
the release command a migration credential:

```yaml
release:
  command: node scripts/migrate.js

databases:
  - database: nest-notes-db
    env: DATABASE_URL
    access: read_write
    create:
      postgres_major: 17
  - database: nest-notes-db
    env: MIGRATION_DATABASE_URL
    access: migration
```

If a migration fails, the previous version keeps serving.

## Validate before the database

A global `ValidationPipe` with `class-validator` DTOs rejects a bad body
with `400` before any query runs:

```ts
app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true,
    forbidNonWhitelisted: true,
    transform: true,
  })
);
```

`forbidNonWhitelisted` also rejects fields the DTO doesn't declare, so a
client can't set a column you didn't mean to expose.

## The example repository

[gregale-dev/nestjs-postgres](https://github.com/gregale-dev/nestjs-postgres)
is a NestJS 12 notes API built this way, with end-to-end tests through Nest's
HTTP pipeline using Node's own test runner:

```bash
git clone https://github.com/gregale-dev/nestjs-postgres
cd nestjs-postgres
gregale deploy --name my-nest-api
```

## What we measured

We deployed that repository on Gregale on 2026-11-30, at 512 MB:

- **Deploy:** 81 seconds from `gregale deploy` to a verified release,
  including creating the database. The app layer is 92 MB.
- **Waking a parked app:** restored from its snapshot in 66 and 74 ms. The
  first byte of `GET /api/notes`, which also had to wake the database, left
  Gregale's edge about 450 ms after the request arrived.
- **Validation:** a note with an empty title got `400` without touching the
  database.

See [Deploy a NestJS app](https://gregale.dev/docs/deploy-nestjs.md) for the reference guide.

## Questions

### Why does NestJS 12 fail with ERR_REQUIRE_ESM or a missing .js import?

NestJS 12 is published as an ES module. Set "type": "module" in package.json, use module and moduleResolution nodenext in tsconfig.json, keep experimentalDecorators and emitDecoratorMetadata on, and import local files with a .js extension.

### Which command should start NestJS in production?

The compiled output, node dist/main, through a start:prod script. Gregale runs npm run build and then npm run start:prod when it exists; a start script that runs nest start --watch or ts-node gets a development_start_command warning.

### Do NestJS and node-postgres work with a transaction-mode connection pooler?

Yes. node-postgres sends unnamed statements, which work in transaction mode. Set idleTimeoutMillis on the pool so the database can suspend when idle, and close the pool in onModuleDestroy with app.enableShutdownHooks().

### How fast does a NestJS app wake on Gregale?

Our NestJS 12 notes API was restored from a snapshot in 66 to 74 ms after being parked. Its first request, which also woke the database, got its first byte about 450 ms after it arrived.

Canonical URL: https://gregale.dev/articles/deploy-nestjs-postgres

