Skip to content

Vite build-time environment variables in Docker and why ARG is unnecessary

Vite embeds import.meta.env variables at build time instead of reading them at runtime. In Docker, this works through the build context, not ARG/ENV. A common mistake with a surprisingly simple solution.

Vite embeds import.meta.env variables at build time instead of reading them at runtime. In Docker, this works through the build context, not ARG/ENV. A common mistake with a surprisingly simple solution.

Contents

The misunderstanding about Vite environment variables

When you use import.meta.env.VITE_SOMETHING in a React + Vite project, it has a property that fundamentally differs from classic Node.js environment variables:

The value is embedded at build time, not read at runtime.

Vite replaces every import.meta.env.VITE_* reference with its value during npm run build. The generated JavaScript bundle contains those values directly as strings, without any remaining reference to environment variables. My article on moduleResolution: bundler and noEmit explains why Vite, rather than tsc, handles the build.

// Source code:
const apiUrl = import.meta.env.VITE_API_URL;

// After the build (in dist/):
const apiUrl = 'http://localhost:3000';

This is a feature, not a bug. It enables tree shaking: code paths that are active only with VITE_AUTH_ENABLED=false do not end up in the production bundle.

The problem with Docker ARG

If you know Vite’s behavior, Docker ARG/ENV seems intuitive:

# Attempt 1: ARG approach
FROM node:20-alpine AS builder
ARG VITE_AUTH_ENABLED=false
ENV VITE_AUTH_ENABLED=$VITE_AUTH_ENABLED
COPY . .
RUN npm run build
# docker-compose.yml
services:
  frontend:
    build:
      context: .
      args:
        VITE_AUTH_ENABLED: ${VITE_AUTH_ENABLED:-false}

This looks right. It is not, however, when the variables should come from a per-project .env file.

The problem is that the shell resolves ${VITE_AUTH_ENABLED:-false} in Docker Compose before Docker Compose processes the file. If the shell has no VITE_AUTH_ENABLED environment variable, the default value false applies. Docker Compose does not read a per-project .env here. It reads only shell environment variables and an optional root .env file.

The result: VITE_AUTH_ENABLED is always false in the Docker build, regardless of what frontend/.env contains.

Docker Compose does not allow env_file under build

A natural next attempt:

# Attempt 2: env_file under build (not supported)
services:
  frontend:
    build:
      context: ./frontend
      env_file: ./frontend/.env # Error

Docker Compose v2.38.2, and all current versions, do not support env_file under the build block:

additional properties 'env_file' not allowed

env_file works at service level for runtime variables, not under build for build-time variables. This is a known limitation.

The correct solution using the build context

The solution is surprisingly simple and requires no changes to Docker Compose or the Dockerfile.

Step 1: check what ends up in the build context.

frontend/
  .dockerignore
  Dockerfile
  package.json
  src/
  .env          # Included by COPY . .?
# frontend/.dockerignore
node_modules/
dist/

node_modules/ and dist/ are excluded. .env is not listed in .dockerignore, so COPY . . copies it into the container.

Step 2: Vite reads .env automatically.

FROM node:20-alpine AS builder
WORKDIR /app
COPY . .             # .env is now in the container
RUN npm ci
RUN npm run build    # Vite reads .env and embeds the values

When Vite runs npm run build, it automatically looks for .env, .env.local, .env.production and similar files in the working directory. It finds frontend/.env, because the container WORKDIR is /app and COPY . . copied everything there, and reads the values.

No ARG, no ENV and no Compose configuration needed.

The only pitfall with no-cache after changes

Docker caches build layers. If frontend/.env changes but no other files do, Docker may reuse the cached layer without reading the new .env.

Always build with --no-cache after changes to frontend/.env:

docker compose build --no-cache frontend && docker compose up -d frontend

Alternatively, invalidate the relevant layer by changing another file, such as package.json. That is less practical.

Verification

To ensure the correct values ended up in the bundle:

# Check whether AUTH_ENABLED is set correctly
grep -r "auth-disabled" dist/assets/

# Or positively: check whether the real client ID is in the bundle
grep -r "VITE_ZITADEL_CLIENT_ID" dist/assets/  # Should return no matches
grep -r "your-client-id-value" dist/assets/     # Should return matches

If "auth-disabled" appears in the bundle even though .env contains VITE_AUTH_ENABLED=true, Docker used the cached layer. --no-cache fixes this.

Does this mean .env should not be in .gitignore for Docker projects?

No. The .env file contains secrets, such as client IDs and API keys, and does not belong in the Git repository.

The approach is to commit .env.example, put .env in .gitignore and have the CI/CD pipeline inject values through real secrets. GitHub Actions Secrets are written to frontend/.env before the build.

# GitHub Actions example
- name: Create frontend .env
  run: |
    echo "VITE_AUTH_ENABLED=true" > frontend/.env
    echo "VITE_ZITADEL_CLIENT_ID=${{ secrets.ZITADEL_CLIENT_ID }}" >> frontend/.env
    echo "VITE_ZITADEL_DOMAIN=${{ secrets.ZITADEL_DOMAIN }}" >> frontend/.env

The Docker build then works just as it does locally, except that the CI pipeline generates .env instead of someone creating it manually.

Why there is no root .env

Many projects have a root .env configuring all services. This is convenient initially. This project deliberately uses per-project .env files:

  • frontend/.env: Vite variables for the frontend
  • extension/.env: Vite variables for the Chrome Extension
  • backend/.env: Node.js variables for the backend

Each service has its own scope. Changes to frontend variables do not affect the backend Dockerfile. Running docker compose build frontend is sufficient; no rebuild of all services is needed.

Vite reading .env from the Docker build context _Figure: Docker Compose copies the build context, including .env, into the container. There, npm run build runs Vite. Vite automatically reads .env and embeds all VITE_\* variables in the JavaScript bundle. The finished bundle no longer contains environment-variable references. The original diagram retains its German text._


All articles in the series

  1. Vision and system overview: Chrome Extension, RAG architecture and project background: Read article
  2. Building a RAG system: Qdrant, embeddings and cosine similarity in TypeScript: Read article
  3. AI provider abstraction: Ollama vs. OpenAI, interface design and no vendor lock-in: Read article
  4. Chrome Extension MV3: Three isolated runtime contexts, message passing and Strategy Pattern: Read article
  5. Docker Compose strategy: The override pattern, from local development to Azure: Read article
  6. Ollama locally vs. Docker: The decision and its consequences: Read article
  7. Ollama auto-pull entrypoint: Automated model setup at container startup: Read article
  8. tsconfig and Vite: Node16 vs. bundler, and why Vite has its own rules: Read article
  9. Load complete Instagram captions with MutationObserver: Read article
  10. Chrome Extension foundation with health indicator and retry queue: Read article
  11. Phase 2 features: Shadow DOM overlay, Tailwind v4 and duplicate detection: Read article
  12. Race condition in platform detection: How a UI event breaks Instagram detection: Read article
  13. Extracting PostId in two Instagram layouts: querySelector vs. ancestor traversal: Read article
  14. Capture a complete Instagram carousel with MutationObserver: Lazy loading, observer-before-click and timeout fallback: Read article
  15. Notes and tags when saving screenshots: Read article
  16. Instagram keyboard shortcuts block Chrome Extension input: Read article
  17. Lowercase normalization and duplicate detection in tag input: Read article
  18. Zitadel Login V2 in Docker Compose with three hidden errors: Read article
  19. PKCE OAuth in a Chrome MV3 extension: Read article
  20. React frontend with react-oidc-context and Zitadel: Read article
  21. Vite build-time environment variables in Docker: (this article)
  22. Event-driven ingestion with BullMQ and Redis: Read article
  23. MinIO instead of Azurite: S3-compatible object storage locally and on Hetzner: Read article
  24. access_token, id_token and the Userinfo endpoint: Which belongs where: Read article
  25. Qdrant multi-tenancy with one collection per user: Read article
  26. When backend and frontend know different types: Read article
  27. Removing Zitadel bootstrap: Host header bug and manual setup: Read article
  28. Backend code review with six problems fixed before launch: Read article
  29. Traefik instead of NGINX: Reverse proxy for a growing Docker Compose stack: Read article
  30. Two-layer rate limiting: Traefik and express-rate-limit with Redis: Read article
  31. Implementing GDPR Article 17 correctly: Promise.allSettled and export batching: Read article
  32. Embedding model lock-in: Why mxbai-embed-large is a permanent production decision: Read article
  33. Docker volumes in production: Named volumes, bind mounts and the Hetzner volume approach: Read article
  34. Two vulnerabilities before launch: Redis without authentication and an exposed Qdrant admin port: Read article
  35. Traefik as the single entry point in the Docker Compose stack: Read article
  36. Connecting Zitadel behind Traefik with issuer, JWKS and Login V2: Read article
  37. Fixing the frontend when the nginx healthcheck fails on localhost: Read article
  38. Observability for my Docker Compose stack with Bull Board and Dozzle: Read article
  39. Open the Qdrant dashboard securely with local Traefik and an SSH tunnel: Read article
  40. Diagnosis of chunking failures despite tokenization: Read article
  41. Why I set the chunk size to 1500 tokens: Read article
  42. Splitting the embedding workflow into clear steps: Read article
  43. Bringing chunking, storage and search back together: Read article
  44. Capture Intake as a separate module, less orchestration in the Express endpoint: Read article

Are you building a Vite frontend in Docker and struggling with environment variables? Let us assess it together.

Related posts

What should your portal do?

Describe your workflow. Together, we will identify the right next step.

Discuss your workflow