Skip to content

fix: support bracket notation for env var replacement in Vite define#696

Open
RobSchilderr wants to merge 2 commits into
onejs:mainfrom
RobSchilderr:fix/env-bracket-notation-replacement
Open

fix: support bracket notation for env var replacement in Vite define#696
RobSchilderr wants to merge 2 commits into
onejs:mainfrom
RobSchilderr:fix/env-bracket-notation-replacement

Conversation

@RobSchilderr
Copy link
Copy Markdown
Contributor

Problem

Vite's define config performs literal text replacement on source code. The clientEnvDefine object in loadEnv.ts currently only generates dot-notation keys:

`process.env.${key}`
`import.meta.env.${key}`

This means bracket notation access — which is common in TypeScript codebases where noPropertyAccessFromIndexSignature is enabled — is never replaced and resolves to undefined at runtime:

// ✅ Works — replaced by Vite
process.env.ONE_PUBLIC_POSTHOG_KEY

// ❌ Broken — not replaced, becomes undefined
process.env["ONE_PUBLIC_POSTHOG_KEY"]

TypeScript's noPropertyAccessFromIndexSignature compiler option (part of strict configs) requires bracket notation for index signatures, which makes process.env["KEY"] the natural way to access env vars. This creates a subtle bug where env vars silently resolve to undefined in client bundles.

Fix

Add bracket-notation entries (both double and single quotes) to the clientEnvDefine output for both process.env and import.meta.env:

return [
  [`process.env.${key}`, stringified],
  [`process.env["${key}"]`, stringified],
  [`process.env['${key}']`, stringified],
  [`import.meta.env.${key}`, stringified],
  [`import.meta.env["${key}"]`, stringified],
  [`import.meta.env['${key}']`, stringified],
]

Note: Metro's Babel plugin (import-meta-env-plugin.ts) already handles both notations via AST analysis, so this only affects the Vite/web path.

Vite's `define` config performs literal text replacement. The current
`clientEnvDefine` only generates dot-notation keys (e.g.
`process.env.FOO`), so bracket notation (`process.env["FOO"]`) is
never replaced and resolves to `undefined` at runtime.

This adds bracket-notation entries (both double and single quotes) for
`process.env` and `import.meta.env` so that either access style works
in client bundles.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant