Skip to content
Latchkey

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 build

Gotchas

  • 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

Run this faster and cheaper on Latchkey managed runners. Start free →