Skip to content
Latchkey

Vitest "import.meta.env is undefined" in CI

Vitest exposes Vite-style env through import.meta.env, but only variables Vite knows about (prefixed, or defined in config) are present. In CI, an unset or unprefixed variable makes import.meta.env.X undefined and code reading it throws.

What this error means

Tests fail with "Cannot read properties of undefined (reading 'VITE_API_URL')" or similar, because import.meta.env lacks the expected key in CI.

Vitest
TypeError: Cannot read properties of undefined (reading 'VITE_API_URL')
 ❯ src/api.ts:3:32
      3| const base = import.meta.env.VITE_API_URL

Common causes

The env var is not set or not prefixed

Vite only exposes variables with the configured prefix (default VITE_). An unprefixed or unset variable is not on import.meta.env in CI.

No .env file is present in the CI checkout

Local .env files are often gitignored, so the values exist locally but not on the runner.

How to fix it

Provide env values to the test run

  1. Set the prefixed variables in the workflow env for the test step.
  2. Or define defaults via test.env in the config.
  3. Confirm code reads import.meta.env.VITE_* names that are actually provided.
.github/workflows/ci.yml
env:
  VITE_API_URL: https://api.example.test

Define test env in config

Set stable defaults so tests do not depend on a gitignored .env file.

vitest.config.ts
export default defineConfig({
  test: { env: { VITE_API_URL: 'https://api.example.test' } },
})

How to prevent it

  • Set required prefixed env vars in the CI job.
  • Provide defaults through test.env for values not secret.
  • Do not rely on gitignored .env files in CI.

Frequently asked questions

What causes ""Cannot read properties of undefined (import.meta.env)""?
Vite only exposes variables with the configured prefix (default VITE_). An unprefixed or unset variable is not on import.meta.env in CI.
How do I fix "Cannot read properties of undefined (import.meta.env)"?
Provide env values to the test run

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card