Webpack DefinePlugin "process.env.X is undefined" - Fix Env Inlining
Webpack does not expose process.env to the browser; DefinePlugin text-replaces specific process.env.X references with literal values at build time. If the variable is not set in the CI build environment, it is inlined as undefined - silently, with no error.
What this error means
The build succeeds, but process.env.API_URL (or similar) is undefined at runtime in the browser, so requests go to undefined/.... It works locally where the var is set in your shell but breaks in CI.
// source
fetch(`${process.env.API_URL}/users`)
// after build, API_URL was unset in CI -> inlined as undefined:
fetch(`${undefined}/users`) // requests https://app/undefined/usersCommon causes
Var not set in the CI build environment
DefinePlugin inlines whatever process.env.X holds when the build runs. If CI does not set the variable, it inlines undefined. The build does not fail - it ships a broken value.
DefinePlugin key mismatch
The DefinePlugin definition key ('process.env.API_URL') does not exactly match the reference in source, so the replacement never happens.
How to fix it
Provide build-time env vars and define them
Set the variable in the CI build step and stringify it in DefinePlugin.
// webpack.config.js
new webpack.DefinePlugin({
'process.env.API_URL': JSON.stringify(process.env.API_URL),
}),Set the variable in CI and fail loudly if missing
- run: npm run build
env:
API_URL: ${{ secrets.API_URL }}
# optionally assert presence before build:
# - run: test -n "$API_URL" || (echo "API_URL not set" && exit 1)How to prevent it
- Set every build-time env var in the CI build step, not just locally.
- Stringify values in
DefinePluginand match keys exactly. - Assert required env vars are present before building so a missing one fails loudly.