Skip to content
Team WorkflowChapter 54 / 57Intermediate6 min read

CI/CD & Environments

CI CD pipeline and environment setup, with typecheck, lint, build and tests on every PR, safe deploys, health checks and a separate staging database.

On this page

1. What is this practice?

CI (Continuous Integration) checks every change automatically. CD (Continuous Delivery/Deployment) automatically carries code that passes to an environment. Environments are the separate places where the app runs: local, preview or staging, and production.

2. Why does it matter?

A check that a human has to remember will be forgotten some day. A pipeline does not remember, it just runs every time.

Without a pipelineWith a pipeline
The build worked on my laptopBuilt on a clean machine on every PR
Forgot to run the testsTests are required on every PR
Staging and production share one databaseEach environment has its own database
Deploy deletes the old folder firstThe new release goes in a separate folder, then switch
No idea if the deploy workedIf the health check fails, the deploy fails
Secrets in the scriptSecrets in CI's encrypted settings

3. When to follow it

LevelHow importantWhy
Learning projectOne simple workflow: install, lint, buildThe idea of a pipeline makes sense in your first project
Production codeThe full pipeline, staging, health checkLower risk on every deploy
Senior levelDeploy strategy, rollback, migration gatesAvoiding downtime and data loss

4. Bad vs good code

Bad: deploy script

bash
ssh server "rm -rf /var/www/app"
scp -r ./build server:/var/www/app
ssh server "cd /var/www/app && npm run migrate && npm run seed"

The old folder is deleted first, the migration runs without a backup, and seed data goes into production.

Good: CI workflow

yaml
name: ci
on:
  pull_request:

permissions:
  contents: read

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version-file: .nvmrc
      - run: npm ci
      - run: npx tsc --noEmit
      - run: npx eslint . --max-warnings=0
      - run: npx prettier --check .
      - run: npm run build
      - run: npm test

The secret scan and migration dry run come into this same file as separate steps.

Good: health endpoint

ts
export async function GET() {
  const missing = ["DATABASE_URL", "SESSION_SECRET"].filter((key) => !process.env[key]);
  if (missing.length > 0) {
    return Response.json({ ok: false, missing }, { status: 503 });
  }

  try {
    await db.$queryRaw`SELECT 1`;
  } catch {
    return Response.json({ ok: false, database: "down" }, { status: 503 });
  }

  return Response.json({ ok: true });
}

What is the difference?

ThingBadGood
DeployDelete the old, then put the newNew in a separate folder, then switch
MigrationNo backupBackup, then migration
SeedOn productionOnly local and test
VerifyHopePoll /api/health, fail the job if it fails

5. How to apply it

Pipeline stages, in this order

StageNext.js exampleWhy
Installnpm ciExact versions from the lockfile
Secret scangitleaks (version pinned)A leak is caught before merge
Typechecknpx tsc --noEmitType errors
Lint and formateslint --max-warnings=0, prettier --checkWarnings fail too
Buildnpm run buildThe build must not only work on a laptop
MigrationsDry run when migrations changeWrong SQL is caught before production
Testsnpm testContract and logic

CI's Node version should match .nvmrc. Secrets come only from CI's secret settings, in the job level env.

Safe deploy
Tests pass
Build once, upload the artifact
New release in a separate folder
Database backup
Migrations
Switch traffic to the new release
Poll the health check, fail the job if it fails

Environments

  • At least production and one preview or staging, each with a separate database.
  • Keep APP_ENV (local, staging, production) separate from NODE_ENV. Staging also runs with NODE_ENV=production, so identifying the environment from NODE_ENV alone is wrong.
  • Every variable is set on the hosting and mirrored by name in .env.example.

Scheduled jobs

Cron calls a guarded endpoint (with a secret). Have a way to prevent overlapping runs. A cron that spends money (AI calls, SMS) should be idempotent and check a kill switch env variable before it works.

6. Exceptions and common mistakes

When the rule does not apply: hosting platforms that deploy from git on their own (like Vercel) handle release folders and switching themselves. There your job is to keep the pipeline and env variables correct. Mobile store builds run from a manual trigger, not from a commit.

Mistake: Making lint and tests an optional stage

Why? Optional means they stop running after the first week.

Better: Required stages on every PR, and merging is blocked when red.

Mistake: One database for staging and production

Why? A delete tested on staging wipes production data.

Better: Each environment gets its own database and its own secrets.

Mistake: Treating a deploy as successful without a health check

Why? The process started but cannot reach the database, and users are getting 500s.

Better: The deploy job polls the health endpoint and fails if it fails.

7. What to learn before and after

Final quick revision

CheckYes?
Workflow in the repo root .github/workflows/
Typecheck, lint, build, tests on every PR
Secret scan and migration dry run
A separate database per environment
Deploy does not delete the old release
Migration after a backup
/api/health returns 503 when something is missing