AI & LLMs

CI/CD for Node.js With GitHub Actions: Test, Build and Deploy Automatically

Screenshot 2026 04 24 at 5.49.42 PM CI/CD for Node.js With GitHub Actions: Test, Build and Deploy Automatically
On this page
  1. How GitHub Actions works
  2. Step 1: Continuous integration on every push and pull request
  3. Step 2: Integration tests with a real MongoDB
  4. Step 3: Test on several Node.js versions
  5. Step 4: Build the frontend
  6. Step 5: Deploy to a VPS over SSH
  7. Step 6 (alternative): Build and push a Docker image
  8. Secrets and environments
  9. Make the pipeline enforceable
  10. Keeping it fast
  11. Debugging a failed workflow
  12. Status badges and notifications
  13. Frequently asked questions
  14. Oh hi there 👋It’s nice to meet you.
  15. Sign up to receive awesome content in your inbox.

Continuous integration and continuous deployment (CI/CD) means every change is tested automatically, and changes that pass are released automatically. For a Node.js or MERN project, that replaces “I think I ran the tests” and “let me SSH in and pull the latest code” with a repeatable process that runs the same way every time. GitHub Actions is built into GitHub, free for public repositories, and generous for private ones, which makes it the easiest place to start.

This guide builds a complete pipeline step by step: tests on every pull request, integration tests against a real MongoDB, caching to keep it fast, and deployment to a VPS or as a Docker image.

How GitHub Actions works

Term Meaning
Workflow A YAML file in .github/workflows/ describing an automated process
Trigger (on) What starts it: a push, a pull request, a schedule, or a manual button
Job A group of steps that runs on one fresh virtual machine (a runner)
Step One command, or one reusable action such as checking out code
Action A reusable step published by GitHub or the community, such as actions/setup-node
Secret An encrypted value, such as an API key, available to workflows but hidden in logs

Jobs run in parallel by default. Use needs to make one job wait for another, for example “deploy only after tests pass”.

Step 1: Continuous integration on every push and pull request

# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm test

Commit this file and open a pull request: GitHub runs the job and shows a green check or a red cross on the pull request. npm ci installs exactly what your lock file says, and cache: npm reuses downloaded packages between runs, which often cuts install time considerably.

Step 2: Integration tests with a real MongoDB

Unit tests with mocks miss problems that only appear against a real database: missing indexes, wrong queries, duplicate key errors. GitHub Actions can start a MongoDB container next to your job with service containers:

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      mongo:
        image: mongo:7
        ports:
          - 27017:27017
        options: >-
          --health-cmd "mongosh --quiet --eval 'db.runCommand({ ping: 1 })'"
          --health-interval 5s
          --health-timeout 5s
          --health-retries 10
    env:
      MONGODB_URI: mongodb://127.0.0.1:27017/test
      NODE_ENV: test
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22, cache: npm }
      - run: npm ci
      - run: npm test

The health check makes the job wait until MongoDB actually accepts connections, avoiding flaky “connection refused” failures at the start of the tests. Note 127.0.0.1 instead of localhost, for the reasons explained in fixing MongooseServerSelectionError.

Step 3: Test on several Node.js versions

If you publish a library, or plan a Node.js upgrade, a matrix runs the same job on several versions at once:

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node: [20, 22, 24]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
          cache: npm
      - run: npm ci
      - run: npm test

Add an os dimension with ubuntu-latest, windows-latest and macos-latest to catch platform-specific bugs, such as file path or file name case problems.

Step 4: Build the frontend

In a MERN project, make sure the React build succeeds on every change. A broken build caught in a pull request is far cheaper than one discovered during a release:

  build-client:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
          cache-dependency-path: client/package-lock.json
      - run: npm ci
        working-directory: client
      - run: npm run build
        working-directory: client
      - uses: actions/upload-artifact@v4
        with:
          name: client-dist
          path: client/dist

Uploading the build as an artifact lets a later deploy job download exactly the files that were tested, rather than building again.

Step 5: Deploy to a VPS over SSH

For an app running with PM2 on a VPS, add a deploy job that runs only for pushes to main, and only after tests and the build pass:

  deploy:
    needs: [test, build-client]
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: production
    concurrency: production-deploy
    steps:
      - name: Deploy over SSH
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SERVER_SSH_KEY }}
          script: |
            set -e
            cd ~/apps/shop
            git pull --ff-only
            npm ci --omit=dev
            npm run build --prefix client
            pm2 reload shop

set -e stops the script at the first failing command, so a failed install never reloads a half-updated app. concurrency prevents two deploys from running at the same time if you push twice quickly. The server setup itself, with Nginx, HTTPS and PM2, is covered in the Node.js production checklist.

Step 6 (alternative): Build and push a Docker image

If you deploy containers, build an image on every push to main and push it to GitHub Container Registry:

  docker:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v6
        with:
          push: true
          tags: ghcr.io/${{ github.repository }}:${{ github.sha }}

Tagging images with the commit SHA means every deployed version maps to an exact commit, which makes rollbacks precise: deploy the previous SHA. Your hosting platform or server can then pull the new image.

Secrets and environments

  • Add secrets under Settings → Secrets and variables → Actions. They are masked in logs and never available to pull requests from forks.
  • Create a production environment under Settings → Environments. Environment secrets are only available to jobs that declare environment: production, and you can require a manual approval before such jobs run.
  • Use a dedicated SSH key for deployments, and a server user that can only manage the app, not the whole machine.
  • Prefer short-lived credentials where your cloud provider supports them, through OpenID Connect, instead of long-lived access keys stored as secrets.

Make the pipeline enforceable

CI only protects you if broken code can’t be merged. In Settings → Branches, add a protection rule for main that requires pull requests and requires the test and build-client checks to pass. Now every change is tested before it reaches production, including your own late-night fixes.

Keeping it fast

  • Cache npm with actions/setup-node, as shown above.
  • Run independent jobs in parallel, such as linting, unit tests and the client build.
  • Use paths filters so documentation-only changes don’t run the full pipeline.
  • Cancel outdated runs when new commits arrive on the same branch, with concurrency and cancel-in-progress: true.
  • Keep slow end-to-end tests in a separate workflow that runs on main or on a schedule.

Debugging a failed workflow

When a run fails, open it in the Actions tab and expand the red step. The log shows the exact command output, just as in your terminal. A few habits make failures much easier to understand:

  • Reproduce locally with the same commands. Run npm ci and npm test exactly as the workflow does. Many “works on my machine” failures come from a lock file that isn’t committed, or from a dependency installed globally on your laptop.
  • Check environment differences. CI runs on Linux with a clean environment: no .env file, case-sensitive file names and a fresh database. Missing environment variables are the most common cause of tests that only fail in CI.
  • Turn on debug logging by re-running the job with “Enable debug logging” checked, which prints much more detail about each step.
  • Upload test reports and screenshots as artifacts when end-to-end tests fail, so you can see what the browser showed.
  • Fix flaky tests immediately. A test that fails randomly teaches the team to ignore red builds, which defeats the purpose of CI.

Status badges and notifications

Add a status badge to your README so anyone can see at a glance whether main is healthy. On the workflow’s page, open the menu and choose “Create status badge” to copy the Markdown. GitHub emails you when your own workflow runs fail, and you can send messages to Slack or other chat tools from a final step that runs only on failure, using if: failure(). Keep notifications for failures only; messages for every successful run quickly become noise that nobody reads.

Frequently asked questions

Is GitHub Actions free?

It is free for public repositories. Private repositories get a monthly allowance of free minutes depending on your plan, and additional minutes are billed. Check GitHub’s current pricing for exact numbers.

What is the difference between CI and CD?

Continuous integration automatically tests and builds every change. Continuous delivery or deployment automatically releases changes that pass, either to a staging environment or directly to production.

How do I run a workflow manually?

Add workflow_dispatch: under on:. A “Run workflow” button then appears on the workflow’s page in the Actions tab.

Why does npm ci fail in CI but npm install works locally?

npm ci requires package.json and package-lock.json to match exactly. Run npm install locally and commit the updated lock file.

Should I deploy automatically to production?

Many teams deploy every passing change to a staging environment automatically and require a manual approval for production. As your test coverage and confidence grow, fully automatic production deploys become safe and save a lot of time.

logo

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox.

We don’t spam! Read our privacy policy for more info.

Saurabh

Saurabh Pathak is an AI engineer and MERN stack developer, and the founder of mernstackdev.com. He builds open-source projects such as the Haat gateway and MCP safety tooling, and he writes hands-on tutorials on React, Node.js, MongoDB and AI agents. He cares most about code that works in production.