What you'll learn: By the end of this lesson you will be able to split a front-end pipeline into verify, build, release and promote stages, explain why a front end should be built once and the same artifact promoted, use lockfile-exact installs and dependency caches without poisoning them, order a deploy so that assets land before the HTML that names them, limit what a workflow can do with permissions, environments and short-lived credentials, and stop two deploys from overtaking each other.
Think of a bakery that supplies several shops. The sensible bakery bakes a batch once, seals the box, and sends the same box to every shop. A bad one re-bakes at each shop with whatever flour is on the shelf, and then wonders why the cakes differ. A front-end pipeline is the bakery: the thing you tested must be the thing you ship.
The running example is the storefront of the ShopStream grocery marketplace: a product page with a search box, a basket and a checkout, built with a bundler into a folder of static files (hashed JavaScript and CSS, plus an HTML shell) and served through a CDN.
The core idea
- CI answers "is this change safe to merge?" It runs on every change, fast, and fails loudly. CD answers "how does a passing commit become what users run?" It turns the commit into a versioned artifact and moves it through environments.
- Build once, promote the artifact. Rebuilding per environment means production runs code nobody tested. Differences between environments belong in configuration, not in a second build (the lesson on runtime configuration and environments covers how; it is a separate lesson).
- A deploy has an order. Static assets are uploaded first and are named by content, the HTML that points at them goes last, and old assets stay for a while. The pipeline enforces that order so a person cannot get it wrong at 2 a.m.
The stages
| Stage | The question it answers | Typical checks | If it fails |
|---|---|---|---|
| Verify | Does it install, compile and pass? | Lockfile-exact install, lint, type check, unit and component tests | Block the merge |
| Build | Can it be bundled, and how big is it? | Production build, bundle-size budget, the artifact itself | Block the merge |
| Preview | Does it work in a real browser? | Per-change deploy, end-to-end smoke test, visual diff | Block or warn, by policy |
| Release | Can it go to users? | Upload assets, then HTML, behind an approval where needed | Stop, keep the old version live |
| Promote and watch | Is it healthy in production? | Smoke test, error rate, rollback hook | Roll back (see the next lesson) |
Not every check belongs in every stage. Testing Pyramid and Trophy guides what is cheap enough for every change and what waits for a preview; End-to-End Testing and Flakiness explains why a flaky browser test should not block unrelated work.
Figure 1. A pipeline that builds once
How to read this: the build box appears once. Preview and production receive the same artifact, so whatever the smoke test saw is what users get. Only configuration, never code, differs between them.
Why build once
A front-end bundle contains whatever the build saw: dependency versions, environment variables read at build time, the minifier's output. Rebuild for production and any of those can differ from what the tests ran against. Building once removes that class of bug and makes rollback cheap, because the previous artifact still exists unchanged.
The catch is configuration. Anything a bundler substitutes at build time (an API base URL, say) is frozen into the artifact. Either the value is the same in every environment, or the app reads it at runtime from a config file or endpoint, the subject of the lesson on runtime configuration and environments.
Illustration 1: the minimal example
The reason "same artifact" can be checked at all is content hashing: a build names each file after a digest of its contents. Run in Node:
import { createHash } from "node:crypto";
const hashOf = (text) => createHash("sha256").update(text).digest("hex").slice(0, 8);
const v1 = "export const price = (cents) => cents / 100;";
const v2 = "export const price = (cents) => (cents / 100).toFixed(2);";
console.log("build 1:", "price." + hashOf(v1) + ".js");
console.log("build 2 (same source):", "price." + hashOf(v1) + ".js");
console.log("build 3 (changed source):", "price." + hashOf(v2) + ".js");
Output, from running it in Node 26.13.1:
build 1: price.2bd3ae77.js
build 2 (same source): price.2bd3ae77.js
build 3 (changed source): price.7aa836b4.js
Same bytes give the same name; changed bytes give a new name. That lets a CDN cache the file for a very long time and a deploy replace it without a purge (see CDN and Edge Caching). Real bundlers hash differently and may not produce identical output on every machine, so this is the idea, not a guarantee about your build; the lesson on bundlers and build tooling covers reproducibility.
Installs and caches
CI should install exactly what the lockfile says. The npm documentation says npm ci requires an existing package-lock.json or npm-shrinkwrap.json, exits with an error instead of updating the lock when it and package.json disagree, removes an existing node_modules first, and never writes to package.json or the lockfiles. A mismatch fails the build rather than quietly changing what is tested. Dependency and Supply-Chain Security covers install scripts and --ignore-scripts.
Caching the package download cache makes installs fast. GitHub's documentation describes the rules:
- The
cacheaction looks for an exactkeymatch first, then falls back torestore-keys. A key such asnpm-${{ hashFiles('package-lock.json') }}changes when the lockfile changes. - A run restores caches from its own branch and its base or default branch, not from sibling branches; caches from a
pull_requestrun are scoped to the merge ref. - Caches not accessed for 7 days are removed; the default limit is 10 GB per repository, evicting the least recently accessed first.
- Do not cache secrets: anyone who can open a pull request can read cache contents.
What a pull request actually tests
A pull_request workflow runs on the merge of your branch into its base, not on your branch alone: GitHub documents that GITHUB_SHA for this event is the last merge commit of the pull request merge branch and GITHUB_REF is refs/pull/<number>/merge. A green branch can therefore turn red after another change lands, because the test ran on a merge that is no longer current.
Illustration 2: the realistic example
For the storefront, one workflow does verify and build on every change, and releases only from the main branch. This is a sketch of a GitHub Actions workflow. Not run: CI cannot be run locally in this course, so the file below is checked against the documentation only. Action versions are shown as placeholders (pin each to a full commit SHA, as the hardening guide advises), and the two scripts/ files are your own.
name: storefront
on:
pull_request:
push:
branches: [main]
permissions:
contents: read # default for every job; raise per job
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@<full commit SHA>
- uses: actions/cache@<full commit SHA>
with:
path: ~/.npm
key: npm-${{ hashFiles('package-lock.json') }}
restore-keys: npm-
- run: npm ci
- run: npm run lint && npm run typecheck && npm test
- run: npm run build
- uses: actions/upload-artifact@<full commit SHA>
with:
name: storefront-dist
path: dist
release:
needs: verify
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production # approval rules apply here
concurrency:
group: release-production
cancel-in-progress: false # never cut a release off halfway
permissions:
id-token: write # short-lived cloud credentials (OIDC)
contents: read
steps:
- uses: actions/download-artifact@<full commit SHA>
with:
name: storefront-dist
path: dist
- run: ./scripts/upload-assets.sh dist # hashed files first
- run: ./scripts/publish-html.sh dist # index.html last
- run: ./scripts/smoke-test.sh # fetch the live page
What the documentation says about the keys used:
needsmakes a job wait for another; if that job fails or is skipped, the dependent job is skipped unless it uses a conditional such asalways().- The
ifexpression stops a job running unless the condition is met. - A job that references an
environmentmust pass all of that environment's protection rules before it is sent to a runner. Environments can require up to 6 reviewers (one approval suffices), add a wait timer, and restrict which branches and tags may deploy. Environment secrets are available only to jobs that use the environment, after the rules pass. Plan limits apply to private repositories. - A
concurrencygroup allows one running job per group; a newly queued job replaces an older pending one, andcancel-in-progress: truealso cancels the running one.
The deploy order
Some platforms make a deploy atomic: Netlify documents that no changes go live until all have been uploaded. On a bucket plus CDN you do the ordering yourself.
Figure 2. The safe order of a release
How to read this: until the HTML changes, users see the old version, so the asset upload is invisible. After the HTML changes, every file it names already exists. Undoing a release is one more HTML publish, because the old assets were never removed.
Two rules follow. HTML must not be cached long in the browser, or users keep pointing at old assets; Vite's documentation says to set Cache-Control: no-cache on the HTML for that reason. And old assets must outlive the HTML that names them: a pipeline that deletes the previous build's files breaks every open tab, the subject of Blue-Green and Canary Releases, and Rollbacks.
Trust: secrets, permissions and forks
A pipeline holds the keys to production, so treat it as part of the attack surface.
- Least privilege. Setting any scope in
permissionssets every unspecified scope tonone, at workflow or job level. GitHub advises making the default token read-only for repository contents and raising it per job. - No long-lived cloud keys. With OpenID Connect, GitHub documents that the job receives a short-lived token valid for a single job, and the cloud provider checks its claims (such as
sub, which can name the repository and environment) against a trust policy. Requesting the token needsid-token: write, which grants no other write access. - Forks. For
pull_requestfrom a fork, secrets are withheld andGITHUB_TOKENis read-only.pull_request_targetruns in the context of the base branch, and GitHub warns against using it to build or run pull request code because that can expose secrets or enable cache poisoning. - Third-party actions. Without a lockfile for workflow dependencies, the hardening guide recommends pinning an action to a full commit SHA, because a tag can be moved or deleted.
Illustration 3: a failure
A step that puts untrusted text straight into a shell script is an injection point. The hardening guide's example is the pull request title; its preferred fix is an intermediate environment variable. Not run:
# Risky: the title becomes part of the script text before the shell sees it
- run: echo "Building ${{ github.event.pull_request.title }}"
# Safer: the title is data in an environment variable, not script text
- run: echo "Building $TITLE"
env:
TITLE: ${{ github.event.pull_request.title }}
The same care applies to branch names, commit messages and any other field a contributor controls.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Build once, promote | What was tested is what ships; cheap rollback | Configuration must be runtime, not build-time |
| Run everything on every change | Early, complete feedback | Slow pipelines that people route around |
| Dependency cache | Faster installs | Stale or poisoned cache risk; eviction surprises |
| Required approval on production | A human checkpoint | Slower releases; reviewers become rubber stamps |
| Preview per pull request | Real-browser checks before merge | Cost; previews must not touch production data |
| Cancel superseded runs | Less waste | Cancelling a release halfway is dangerous |
Build it
This lesson has no lab: the interesting part, a hosted CI service, cannot be run here, and a simulation would only restate the documentation. The two Node snippets above are plain Node and were run; their output is shown unedited. The workflow YAML and the injection example were not run.
The other side of this topic
The back-end view covers pipelines for services: container images, database migrations, environment promotion and deployment gates, in the back-end lesson on CI/CD pipelines. This lesson stays with what is specific to static front-end output, the browser and the CDN.
In practice: the storefront pipeline
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The storefront team has a pipeline that runs on every push. It lints, tests, builds, and deploys to production with a script that copies dist/ over the live bucket and deletes files that are no longer in it. Merges feel slow (about 25 minutes, illustrative) and the team has started merging two changes back to back.
Starting architecture
Figure 3. Build and deploy in one script
How to read this: the warning boxes are the weaknesses. A single script decides ordering and deletion, and nothing stops two runs from touching the bucket at once.
Options considered
| Option | What it fixes | Risk |
|---|---|---|
| Keep the script, add a lock file | Stops simultaneous runs | Stale locks block releases |
| Separate verify and release jobs with a concurrency group | One release at a time, built once | Queue behaviour must be understood |
| Move to a platform with atomic deploys | Ordering handled for you | Skew and rollback rules differ by platform |
The decision
| Field | Decision record |
|---|---|
| Context | A script builds, copies and deletes in one step, and two runs can overlap. |
| Decision | Split into verify and release jobs. Upload the artifact built in verify. Upload hashed assets first and the HTML last, and do not delete the previous build's assets in the release. Give the release job its own concurrency group with cancel-in-progress off, behind a production environment. |
| Consequences, good | One release at a time; the tested artifact ships; rollback is an HTML republish. |
| Consequences, bad | Old assets accumulate until a separate cleanup job removes them. |
| Revisit when | Deploys need a traffic split, which is the next lesson. |
Rollout and verification
- Add the release job first, without removing the old script, and run it for a few merges to compare.
- Check a live page after each release with the smoke test: HTML returns, every asset it names returns 200.
- Force two merges close together and confirm the second release waits.
- Remove the delete step and add a cleanup that keeps recent builds.
The 2 a.m. failure
Two commits merge a minute apart. With no shared concurrency group both releases run in parallel; the older finishes last and republishes its HTML, so production serves older code than main. Every check is green.
Figure 4. Two releases overtaking each other
How to read this: nothing failed. The last writer wins, and the last writer is the slower, older run. One concurrency group makes the second release wait.
First three checks: (1) compare the live HTML's asset hash with the latest main artifact; (2) look for overlapping release runs; (3) check whether the release job has a concurrency group. Mitigation: re-run the latest release. Follow-up: one release group, and a smoke test comparing the live build id with the expected commit.
Architect's notes
- The artifact is the unit of release. Name it by commit, keep it, and promote it.
- Make the safe order the only order. A script that cannot upload HTML before assets beats a runbook that says not to.
- Keep the default token read-only and raise permissions per job.
- A slow pipeline gets bypassed. Measure it and run expensive checks where they pay.
- Treat contributor-controlled text as data, never as script.
Common mistakes
- Rebuilding for each environment.
- Deleting the previous build's assets in the same release.
- Letting two releases run at once.
- A long-lived cloud key as a repository secret when short-lived tokens are available.
- Using
pull_request_targetto build code from a fork. - Secrets in a cache path.
Key takeaways
- CI proves a change is safe to merge; CD turns a commit into an artifact and moves it through environments.
- Build once and promote the same artifact; environment differences are configuration.
- Install with the lockfile (
npm ci), cache downloads, and never cache secrets. - Upload hashed assets first, HTML last, and keep old assets.
- Use job-level permissions, environments and OIDC to limit what the pipeline can do.
- Put releases in one concurrency group so they cannot overtake each other.
Practice exercises
Exercise 1: Starter (30 min). Run the hashing snippet, change one character in the source, and explain what changes in the file name and what that means for a CDN.
Exercise 2: Intermediate (2 hours). Draw the pipeline for a project you know as a table of stages, the check each runs, and what happens on failure. Mark which checks you would move to after merge.
Exercise 3: Advanced (half day). Write the release job for your own hosting so that assets upload before the HTML, then describe how you would test, without running production, that an interrupted release leaves the old version working.
Related reading
In this course:
- CDN and Edge Caching: why hashed assets and an uncacheable HTML shell make deploys safe.
- Blue-Green and Canary Releases, and Rollbacks: the next step, releasing to part of your traffic and undoing a release.
- Testing Pyramid and Trophy: which tests belong at which stage.
- Dependency and Supply-Chain Security: what you install and run in CI.
- Performance Budgets and Profiling: turning bundle size into a CI check.
Official documentation
- GitHub Docs: Workflow syntax: permissions, concurrency, needs, environment.
- GitHub Docs: Dependency caching: keys, scope and eviction.
- GitHub Docs: Managing environments for deployment: approvals and environment secrets.
- GitHub Docs: OpenID Connect: short-lived cloud credentials.
- GitHub Docs: Security hardening for GitHub Actions: pinning, injection, token permissions.
- npm Docs: npm ci: lockfile-exact installs.