How to Inject Environment Variables at Build Time for a Static Site
A static bundle has no server, so any runtime value must be present at build time under the framework public prefix.
Expose values with the framework prefix (Vite VITE_, Next NEXT_PUBLIC_, Astro/CRA PUBLIC_/REACT_APP_) in the build step. They are inlined into the bundle, so never put secrets there.
Steps
- Store the value as a CI variable (public config, not a secret).
- Pass it with the framework public prefix to the build.
- Reference it in code via the framework env object.
- Rebuild whenever the value changes.
Workflow
.github/workflows/ci.yml
jobs:
build:
runs-on: ubuntu-latest
env:
VITE_API_URL: ${{ vars.API_URL }}
NEXT_PUBLIC_ANALYTICS_ID: ${{ vars.ANALYTICS_ID }}
steps:
- uses: actions/checkout@v4
- run: npm ci && npm run buildGotchas
- Only prefixed vars are exposed to client code; unprefixed ones are dropped at build.
- Anything inlined into the bundle is public; keep real secrets server-side.
- Changing the value needs a rebuild, since it is baked into the static files.
Related guides
How to Build Then Deploy a Static Site in One CI PipelineSplit a static site pipeline into a build job that produces an artifact and a deploy job that consumes it, ke…
How to Set Up Cache Busting and Asset Fingerprinting on DeployFingerprint static assets with content hashes in their filenames so a new deploy ships new URLs, letting you…