HomeBlogHow to Build a CI/CD Pipeline...

Engineering Guide · 9 min read · November 21, 2026

How to Build a CI/CD Pipeline for a Next.js Application

Next.js CI/CD pipelines often crawl because teams rebuild node_modules from scratch, bake staging API URLs into production bundles, or push broken schema changes alongside UI deploys. This guide shows how to structure fast, deterministic GitHub Actions workflows with standalone Docker builds, build-time vs runtime env separation, and post-deploy smoke checks.

Author
Smit Desai
Published
November 21, 2026
Read time
9 min read
Topic
Cloud & DevOps
Services
Custom Web · Mobile Apps · All Services

Nothing erodes developer velocity faster than a 14-minute CI pipeline that still lets a broken production deploy slip through. With Next.js applications—especially App Router apps combining React Server Components, API route handlers, image optimization, and database queries—most CI/CD pain stems from treating Next.js like a plain static site.

Next.js sits awkwardly between frontend and backend: it needs build-time static analysis, strict environment variable hygiene, cache-aware asset syncing, and graceful server rollouts. Here is how to engineer a reliable, fast CI/CD pipeline for Next.js using GitHub Actions, whether you deploy containers to AWS/GCP or self-host on dedicated Linux nodes.

Next.js CI/CD Pipeline Architecture


Understanding the Build-Time vs. Runtime Trap

Before writing a single line of YAML, resolve the #1 cause of broken Next.js releases: where environment variables get evaluated.

Variable Type Evaluated When? Safe for Build Caching Across Envs? Typical Use Case
NEXT_PUBLIC_* next build (inlined into JS) No (frozen per environment) Public Stripe key, PostHog key, public CDN host
Server-only process.env Request runtime (Server Components/API) Yes (read from runtime secret store) DATABASE_URL, STRIPE_SECRET_KEY, JWT secrets
next.config images.remotePatterns next build Yes (code-level config) Allowed S3/CloudFront image domains

Why "Build Once, Promote Everywhere" Breaks NEXT_PUBLIC_

If you build a Docker image with NEXT_PUBLIC_API_URL=https://staging-api.example.com and promote that exact image tag to production, your production users will hit staging APIs. You have two clean solutions:

  1. Build separate environment artifacts (fast when .next/cache is shared) so staging and production compile their own client bundles.
  2. Expose a tiny runtime /api/runtime-config endpoint or server-injected script for non-secret public endpoints so one immutable container image promotes cleanly from staging to production.

Enabling standalone Output in next.config.ts

If you ship Next.js via Docker instead of a managed PaaS, enable standalone output immediately. Next.js uses @vercel/nft to trace only the exact files inside node_modules required to boot the server:

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
  poweredByHeader: false,
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "cdn.yourdomain.com",
      },
    ],
  },
};

export default nextConfig;

Remember one crucial quirk of standalone: it does not automatically copy public/ or .next/static/ into .next/standalone/. Your Dockerfile must copy both explicitly, or every stylesheet and font will return 404 after deployment.


A Fast Multi-Stage Dockerfile for Next.js

Pair standalone mode with BuildKit dependency caching and a non-root runtime user:

# syntax=docker/dockerfile:1.7
FROM node:22-alpine AS base
RUN corepack enable && corepack prepare pnpm@9.12.0 --activate
WORKDIR /app

FROM base AS deps
COPY package.json pnpm-lock.yaml ./
RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store \
    pnpm install --frozen-lockfile

FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
RUN pnpm build

FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

RUN addgroup --system --gid 1001 nodejs \
    && adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

CMD ["node", "server.js"]

Setting HOSTNAME="0.0.0.0" is mandatory inside containers; otherwise Next.js may bind to the container's local hostname or 127.0.0.1 and fail load balancer health checks.


Structuring the GitHub Actions Pipeline

A production Next.js workflow should split fast pull-request verification from gated deployment jobs. Never deploy directly from a push without running typechecking, linting, and unit/integration checks in parallel first.

name: Next.js CI/CD

on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
  id-token: write
  contents: read

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
        with:
          version: 9.12.0
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm

      - name: Restore Next.js build cache
        uses: actions/cache@v4
        with:
          path: .next/cache
          key: ${{ runner.os }}-nextjs-${{ hashFiles('pnpm-lock.yaml') }}-${{ hashFiles('src/**/*') }}
          restore-keys: |
            ${{ runner.os }}-nextjs-${{ hashFiles('pnpm-lock.yaml') }}-

      - run: pnpm install --frozen-lockfile
      - run: pnpm typecheck
      - run: pnpm lint
      - run: pnpm test:ci
      - run: pnpm build

  deploy:
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    needs: verify
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4

      - name: Configure AWS credentials via OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }}
          aws-region: us-east-1

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v2

      - name: Build and push immutable image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.login-ecr.outputs.registry }}/web-app:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Run backward-compatible DB migrations
        run: ./scripts/run-migrations.sh

      - name: Update service and wait for stability
        run: |
          aws ecs update-service \
            --cluster prod-cluster \
            --service nextjs-web \
            --force-new-deployment
          aws ecs wait services-stable \
            --cluster prod-cluster \
            --services nextjs-web

Key Pipeline Design Choices

  • Cancel stale PR runs, never main deploys: cancel-in-progress prevents wasted CI minutes on rapid PR pushes while protecting main deployments from being aborted mid-migration.
  • OIDC instead of static secrets: Using id-token: write eliminates long-lived AWS keys in GitHub Secrets—an engineering standard covered extensively on the GitHub Engineering Blog.
  • Caching .next/cache and BuildKit layers: Preserving .next/cache alongside type=gha Docker layer caching typically cuts Next.js CI rebuilds by more than half.

Zero-Downtime Skew Protection and Smoke Checks

When you deploy a new Next.js build behind a load balancer, users with an already-open tab may trigger a Server Action or fetch a chunk hash belonging to the previous release while traffic shifts to the new container.

Three practices keep rollouts painless:

  1. Sync static assets before draining old containers (or store .next/static on S3/CloudFront without --delete on recent hashes for 24–48 hours) so in-flight sessions never hit 404 chunk errors.
  2. Pin a consistent NEXT_SERVER_ACTIONS_ENCRYPTION_KEY across all running container replicas via your secret manager; without it, Server Actions fail during rolling deployments.
  3. Run an automated post-deploy smoke test hitting /api/health and a key rendered page, failing the pipeline and triggering automatic rollback if HTTP 5xx responses appear.

For backend heavy lifting triggered by Next.js routes—such as webhook ingestion or report generation—offload work to dedicated queues rather than extending serverless timeouts; see scaling background jobs and queues with Laravel and Redis for queue isolation mechanics.


Need Help Hardening Your Next.js Delivery Pipeline?

Slow builds, flaky migrations, and manual deploy Fridays drain engineering morale across teams of every size. Whether you are migrating a legacy frontend into modern Next.js via an old software upgrade or building clean CI/CD automation from scratch, SmitDev builds pipelines that stay fast and predictable.

I work hands-on with startups and engineering teams worldwide—at $55/day for 8–9 hours of dedicated engineering work, $1,999/month dedicated delivery, or flexible hourly developer engagements—backed by 170+ shipped case studies. Reach out on the contact page to tighten your Next.js build and release workflow.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

cloud & devops

Why do NEXT_PUBLIC_ environment variables behave differently in a CI/CD pipeline?

Next.js inlines NEXT_PUBLIC_ variables directly into the client JavaScript bundle during next build. If you build one Docker image for staging and promote it to production, those client variables remain frozen at their staging values unless you inject runtime config or build per environment.

Should I run database migrations inside the Next.js container startup command?

No. Running migrations in container entrypoint commands causes race conditions when multiple replicas boot simultaneously. Run backward-compatible schema migrations as an explicit, gated CI/CD job before rolling out the new application revision.

How much faster does output: 'standalone' make Next.js Docker images?

Enabling output: 'standalone' in next.config.ts lets Next.js trace only the production files needed by the server, shrinking final container images from well over 1 GB down to roughly 150–250 MB and cutting deployment pull times sharply.

Can I deploy Next.js without Vercel using GitHub Actions?

Yes. Building a standalone Next.js container via GitHub Actions and deploying to AWS ECS, Cloud Run, or a Docker host behind Caddy/Nginx gives you full control over VPC networking, egress costs, and server timeouts.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.