🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Shipping React Apps: CI/CD, Hosting and Rollbacks

React DevOpsđŸŸĸ Free Lesson

Deployment is not the button at the end of a tutorial, it is the machine that turns a commit into a running application without a human making a decision. Two failure modes dominate React releases. The first is a build treated as a black box, where nobody can say which commit, which node version and which configuration produced the artefact currently serving customers. The second is a release treated as irreversible, so a broken change stays live while engineers reconstruct the previous state by hand from memory. Both fixes are boring and structural: build once and promote the same artefact through environments, keep configuration outside the repository, verify the result with a smoke test, and make rolling back cheaper than arguing about whether the problem is real.

âš ī¸Never build twice for production

Rebuilding the artefact during the deploy step means the code you tested and the code you ship are two different objects. Build in one job, upload the output as an artefact, and let the deploy job consume it unchanged.

Static, server rendered or hybrid

The hosting model you pick decides what is possible later, so choose it from data requirements rather than from whichever framework tutorial you followed. The axis that matters is how fresh and how personal the HTML must be, and how much of the page can be assembled in the browser after load.

ModelWhat runs on requestStrengthsCosts and limits
Static exportNothing, files served from a CDNCheapest, scales without effort, simplest security storyNo server routes, no per-request personalisation, client fetch for all data
Server renderedA Node process renders HTML per requestPersonalised HTML, SEO for fast changing dataPays compute for every request, needs capacity planning
Hybrid with cachingCached HTML plus on-demand renderingFresh where it must be, cached everywhere elseCache policy becomes the thing to get right
Edge renderedA function at the CDN renders HTMLLow latency close to the user, geo awarenessRestricted runtime, cold starts, harder local debugging

A content site or an internal dashboard whose data arrives from an application programming interface on load is usually happiest as a static export behind a CDN. A product application with account specific landing pages wants server or hybrid rendering so the first paint already carries the right content. Whatever you choose, the JavaScript cost of hydration does not disappear: server rendering improves the first meaningful paint and search visibility, while the same components still boot on the client and must stay inside the interaction budget.

An image that serves the build

Containerising a React build buys reproducibility, because the same base image, node version and dependency lock produce the same output on a laptop and on a build agent. The structure that makes this fast is layer discipline: copy the lock files, install, and only then copy sources, so an edit to a component does not invalidate the dependency layer and force a full reinstall.

# Dockerfile
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build

FROM nginx:1.27-alpine AS runtime
RUN addgroup -S app && adduser -S app -G app
COPY --from=builder /app/out /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://localhost/healthz || exit 1
CMD ["nginx", "-g", "daemon off;"]

The runtime stage contains no node, no source and no dev dependencies, which removes a large class of vulnerabilities and shrinks the image by hundreds of megabytes. Pair it with cache headers that match the build output, because correct caching is what makes a static deployment feel instant rather than merely available.

server {
  listen 80;
  root /usr/share/nginx/html;

  location = /healthz {
    return 200 "ok\n";
  }

  location /_next/static/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
  }

  location / {
    try_files $uri $uri.html $uri/ /index.html;
    add_header Cache-Control "no-cache";
  }
}

The pipeline that proves the artefact

A release pipeline should answer three questions before anything reaches a customer: does it build, does it behave, and is it the same bytes we tested. Continuous integration answers the first two with lint, tests and a production build; the artefact upload answers the third. The deploy job then becomes a short, repeatable operation with no compilation step of its own.

Concurrency control matters more than most teams expect. Two overlapping releases can finish in either order, leaving customers on a version nobody chose, so give the production environment a single concurrency group and never cancel an in-flight release. Gate the deploy job behind the protected environment so an approval can be required without editing the workflow.

# .github/workflows/release.yml
name: release
on:
  push:
    branches: [main]

concurrency:
  group: release-production
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm test -- --runInBand
      - run: npm run build
      - uses: actions/upload-artifact@v4
        with:
          name: site-build
          path: out/

  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: site-build
          path: out/
      - run: ./scripts/deploy.sh
        env:
          DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
      - run: ./scripts/smoke.sh
        env:
          BASE_URL: https://www.example.com

The smoke test at the end is the part people skip and then miss. Ten requests that assert the home page returns successfully, the asset manifest resolves, the application programming interface answers, and the version label matches the artefact just deployed will catch a misconfigured host far faster than a user report.

Environment variables without leaks

Client bundles are public. Anything a variable influences at build time is readable by anyone who opens the network tab, so the rule is not "do not commit secrets", it is "do not put secrets where the browser can fetch them". Server side variables belong in the hosting platform's secret store and are injected at runtime; only values that must reach the browser, such as a public analytics identifier, are exposed to it, and those should be prefixed accordingly so the boundary is visible in code review.

The cheap defence is a check that fails the build when a recognisable secret appears in the output. Run it after every build rather than trusting review, because the leak usually arrives through a dependency or a forgotten example file rather than through intent.

# scripts/check-bundle-secrets.sh
set -euo pipefail

patterns='sk_live_|AKIA[0-9A-Z]{16}|-----BEGIN (RSA|OPENSSH) PRIVATE KEY-----'

if grep -REn "$patterns" out/ >/dev/null 2>&1; then
  echo "secret-like string found in build output" >&2
  grep -REn "$patterns" out/ >&2 || true
  exit 1
fi

echo "no secrets detected in build output"

Rotate on a schedule as well as after incidents, and keep per-environment values distinct so a development credential can never accidentally point at production data.

Preview deployments and one command rollbacks

Every pull request deserves its own URL. Preview deployments give reviewers something to click, give designers a place to check the visual result against the design, and give quality assurance an environment that is not fighting developers for staging. Because the preview is built by the same pipeline from the same lock file, it is also early evidence that the production build will succeed.

Rollback is where the whole design is tested. Keep the last several artefacts available and make the rollback operation a redeploy of a known good one, or an alias flip if your platform routes traffic by version. Rehearse it once, because the first time you press it should not be the first time it runs. The constraint that ruins most naive rollbacks is the database: schema changes must be expand and contract, where the new code works against both the old and the new schema, so reverting the application never requires reverting data.

Caching, hashing and the CDN

Browsers distinguish sharply between files whose names carry a content hash and the document that points at them. Hashed assets are immutable and can be cached for a year, which is why fingerprinting exists; the HTML shell must be revalidated so a release becomes visible on the next navigation instead of stranding users on a stale bundle. Getting that pair wrong produces the two classic complaints: returning users who never see new code, and users who see new code against old cached assets.

Compression, lazy loading for anything below the fold and a strict first-load budget complete the picture. Measure the cache hit ratio at the CDN as a real metric, because a hit ratio that quietly dropped after a routing change is invisible in application logs while doubling your delivery cost.

Before you call it production

A release is complete when the operating story exists, not when the files are on the server. Confirm there is a health endpoint your platform can probe, structured logs with the release identifier attached, error tracking with source maps so a stack trace names a line rather than a chunk, and an uptime check originating outside your own network so a broken routing rule somewhere between the CDN and the origin still pages someone. Walk the rollback once in staging, verify the secret rotation procedure, and write the release notes where the next person will find them.

Common Mistakes

Rebuilding the project inside the deploy job so the artefact differs from the one that was tested

Fix: Build once, upload the output as an artefact, and let the deploy job consume those exact bytes.

Putting server credentials in any variable the browser can read at build time

Fix: Inject secrets at runtime from the platform store and fail the build when a secret pattern appears in the output.

Treating rollback as an emergency improvisation

Fix: Keep recent artefacts available, rehearse the redeploy, and make schema changes backward compatible so reverting code is always safe.

Serving hashed assets and the HTML shell with the same cache header

Fix: Make fingerprinted assets immutable for a year and revalidate the HTML, so releases propagate on the next navigation.

Best Practices

  • Lock the node version and dependency tree so a build on a laptop and a build on an agent produce identical output
  • Gate production deploys behind a protected environment and a single concurrency group so releases never race
  • Run a smoke test after every deploy that checks the home page, the asset manifest and the version label
  • Keep configuration per environment and rotate credentials on a schedule, not only after an incident
  • Ship small, reversible releases, because the ability to roll back quickly is worth more than the size of a single change

Key Takeaways

  • Choose the rendering model from data freshness and personalisation needs, not from tutorial momentum
  • Multi-stage images with layer discipline give reproducible builds, small runtime images and honest health checks
  • The pipeline must build once, test the artefact, deploy those same bytes and verify with a smoke test
  • Client bundles are public property, so secrets belong in runtime configuration and output scanning is the cheap insurance
  • Preview URLs make review concrete, and a rehearsed rollback with expand and contract schema changes makes releases safe
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement