Skip to content

Node deploy hooks on PaaS: pre/post-deploy migrations and asset compilation

Running database migrations and asset builds at the right deploy phase prevents the 'half the fleet sees the new schema, half doesn't' incident. Here is the hook order that works.

You deploy a Node service to a PaaS that rolls containers one by one — six containers, replaced over four minutes. A migration adds a NOT NULL column to users. Container 1 boots, runs the migration in its start hook, and serves traffic against the new schema. Containers 2-6 are still on the old code, writing rows without the new column, and the database starts throwing constraint violations on container 1’s writes because of related foreign keys. The migration ran. It ran on the wrong boundary. The container is the wrong place — the deploy is.

What’s happening

A PaaS deploy has three phases the operator can attach work to: build (runs once, before any container boots, on a build container), pre-deploy (runs once, on a release container or admin node, before the rollout starts), and post-deploy (runs once, after the rollout reports healthy). Containers themselves should run only the application — not migrations, not asset builds, not seed scripts. The reason is the failure mode above: if container start does the migration, you have N containers all trying to migrate the same database concurrently, and the rollout is no longer atomic.

The conventional mapping:

  • Build phase owns code-only work: install dependencies (npm ci), compile assets (webpack, vite, esbuild), tree-shake, minify, generate a build manifest. Runs in a clean container that has source code and build-time secrets but no database access. Output is the artifact the platform deploys.
  • Pre-deploy phase owns the work that must complete before any new container takes traffic: database migrations (forward-compatible only — never DROP COLUMN here), cache warmups that don’t change between containers, search index population. Runs once. If it fails, the deploy aborts and the old containers keep serving.
  • Post-deploy phase owns the work that should run after the new code is live and healthy: cache invalidation broadcasts, CDN purges, scheduled-job re-registration, notification webhooks (Slack, status page).

The container start path stays empty of one-shot work. Containers boot, connect to the database, register with the load balancer, and serve. That’s it.

The other thing to get right is migration safety in a rolling deploy. During the rollout window, old and new code share the database. A migration that breaks the old code (renaming a column the old code reads, adding a NOT NULL constraint without a default) breaks the half of the fleet still on old code. The mitigation is the expand/contract pattern: deploy 1 adds the new column with a default, deploy 2 starts writing to it, deploy 3 backfills, deploy 4 makes it NOT NULL, deploy 5 stops reading the old column, deploy 6 drops the old column. Each deploy is forward-compatible. The pre-deploy hook only ever does additive, safe-to-roll-back work — destructive operations happen during a maintenance window or as a separate, planned schema change with the application code already updated.

If the application uses migrations as part of feature flags, do the migration as a separate ticket from the code that depends on it. Migration first, deploy with the column unused. Then the next deploy enables the feature. Two deploys, not one — and the second one rolls back cleanly because the first one is non-destructive.

How to verify

The platform’s deploy log should show the phases as distinct steps. Something like:

[build]       npm ci                                      24s
[build]       npm run build                                8s
[pre-deploy]  npx prisma migrate deploy                    2s
[deploy]      container web.1 started, health ok          12s
[deploy]      container web.2 started, health ok          11s
[deploy]      container web.3 started, health ok          11s
[post-deploy] curl -X POST $SLACK_WEBHOOK ...              <1s

If “migrate” appears next to a container line, the migration is running in the container start path — that’s the failure mode. Move it to pre-deploy.

Whether your platform exposes pre/post-deploy hooks separately from container start. Some do via a release phase, some via a build manifest, some via the platform CLI. Check the platform docs for the term — common ones are “release command” (Heroku-style), “post-deploy script”, “release phase”, “run-once container”, “pre-start hook”. If the platform only exposes container start, fall back to a single dedicated migration container that runs once and exits — the platform should be configured to wait for it before promoting the new release.

Check that the migration tool you use is idempotent and safe to re-run. Knex, Prisma, Drizzle, Sequelize all track applied migrations in a metadata table; running prisma migrate deploy against an already-migrated DB is a no-op. If your migration tool isn’t idempotent, replace it before wiring it into a deploy hook.

The fix

A representative hook YAML for a Node + Prisma application. Adapt the keys to your platform’s descriptor — the structure is what matters:

name: api-service

build:
  hooks:
    install: |
      npm ci --include=dev
    build: |
      npm run build
      npx prisma generate

release:
  # Runs once, on a single container, before any deploy container takes traffic.
  # If this exits non-zero, the deploy aborts.
  pre-deploy:
    image: build-output
    timeout: 300s
    command: |
      set -euo pipefail
      echo "==> Running pending migrations"
      npx prisma migrate deploy
      echo "==> Warming reference data cache"
      node ./scripts/warm-cache.js

deploy:
  strategy: rolling
  max-unavailable: 1
  health-check:
    path: /health
    timeout: 10s
    initial-delay: 15s
  container:
    image: build-output
    command: node server.js
    instances: 3
    env:
      NODE_ENV: production

post-deploy:
  # Runs once, after all containers report healthy.
  hooks:
    notify: |
      curl -sf -X POST "$SLACK_WEBHOOK" \
        -H 'Content-Type: application/json' \
        -d "{\"text\":\":rocket: api-service deployed $(git rev-parse --short HEAD)\"}"
    purge-cdn: |
      curl -sf -X POST "https://api.cdn.example.com/purge" \
        -H "Authorization: Bearer $CDN_TOKEN" \
        -d '{"paths":["/*"]}'

The package.json scripts that pair with this — note that there is no prestart or start:migrate; the application start path is just node server.js:

{
  "scripts": {
    "build": "tsc -p . && npm run build:assets",
    "build:assets": "vite build",
    "start": "node dist/server.js",
    "migrate:deploy": "prisma migrate deploy",
    "migrate:status": "prisma migrate status",
    "seed:reference": "node dist/scripts/seed-reference.js"
  },
  "engines": {
    "node": ">=20.0.0 <21.0.0"
  }
}

For asset compilation that produces a manifest the application reads at runtime, build phase. The manifest is part of the artifact. The application does not regenerate assets on boot — that’s wasted CPU on every container and inconsistent between containers if the build is non-deterministic.

For destructive migrations (drop a column, change a column type, rename a table), don’t try to fit them into the regular deploy pipeline. Schedule them as a maintenance window operation: app reads in compatibility mode, run the migration during a low-traffic window with explicit pre/post checks, app reads in new mode in the next deploy. The “deploy time migration” pattern is for additive, safe-to-rollback changes only.

A few things to monitor once the hook structure is in place:

  • Pre-deploy duration. If it climbs past 30 seconds for routine deploys, your migration set is probably a long backfill — those belong in a one-off job, not the deploy pipeline.
  • Migration drift between staging and production. If prisma migrate status shows applied migrations in production that aren’t in your repo, somebody ran a manual migration on the database. Fix the process gap, not just the symptom.
  • Asset compile time as a leading indicator of build phase regressions. A jump from 8s to 80s is usually a new dependency pulling something heavy in — catch it before it becomes deploy friction.

We wire up build, pre-deploy, and post-deploy phases — plus the rollback runbook — as part of Cloud PaaS and deployment management. Open a scoping conversation to walk through your specific platform.