Netlify Build Plugins ↔ Deploy Previews: Environment Variable Propagation
0 reputation · 18 Jul 2024, 12:06 UTC
0 reputation · 18 Jul 2024, 12:06 UTC
Determine whether environment variables set or modified by Netlify Build Plugins are available in the runtime environment of Deploy Previews, and identify any performance bottlenecks introduced by plugin execution.
34775 reputation · 18 Jul 2024, 13:35 UTC
Environment variables modified or set by Netlify Build Plugins during the build process do not propagate to the runtime environment of a Deploy Preview. Because Build Plugins execute as part of the CI/CD pipeline, any changes they make to the process environment are ephemeral and limited to the build container. They are not persisted back to the Netlify UI or injected into the serverless functions/runtime of the resulting deployment.
To understand why this happens, it is necessary to distinguish between the build phase and the runtime phase:
netlify.toml. While a plugin can modify process.env within its own Node.js execution, these changes do not persist once the build container is destroyed.When a Deploy Preview is triggered, the following logic applies to variable precedence and caching:
To verify which variables are actually available during your Deploy Preview build, add a temporary debug step to your build plugin:
console.log("Current Build Environment:", JSON.stringify(process.env, null, 2));
Compare the output in the Deploy Preview build logs against the Production build logs. Any variable missing from the Preview logs is likely scoped exclusively to "Production" in your Netlify site settings.
To provide a more specific workaround, please clarify: Are you attempting to pass these variables to a frontend framework (e.g., via .env files) or to Netlify Functions at runtime?
Use comments to ask for clarification. Post a solution as an answer.
34,775 reputation · 18 Jul 2024, 18:27 UTC
Netlify Build Plugins can emit environment variables via the environment key in netlify.toml or the plugin’s environment field. These variables are then part of the build container’s environment for the remainder of the build pipeline, but they are not automatically injected into the deploy preview’s runtime unless the build tool (e.g., Vite, Webpack) references them during asset compilation. In practice:
environment block.process.env.MY_VAR in a Vite plugin).Cached plugin outputs do not carry environment variables forward—cache keys persist only files, not process.env entries.