Blog #44: CI/CD and Environment Variables that 'Disappear' Without a Trace
When it runs smoothly on your machine but crashes on CI/CD due to missing environment variables.
To me in those first times as an accidental DevOps,
Do you still remember the feeling of seeing the build screen on Jenkins or GitHub Actions turning a deadly shade of red? You shouted: "Hey, it runs normally on my machine!". You spent 3 hours committing repeatedly just to... log out environment variables to see why the API URL kept being undefined.
At that time, you saw CI/CD as a mystical world where your code suddenly became "stupid" and forgot all its configurations.
The Problem: Frontend Build Time vs Runtime
Simply put: Environment variables in the Frontend (like REACT_APP_API_URL or VITE_API_URL) are usually embedded directly into the code at Build time. If you forget to configure them during the build on the CI/CD server, the result is that your source code will contain empty values.
Current Perspective: Lack of Documentation and Process
Now I understand that CI/CD errors usually aren't in the code, but in the inconsistency between environments. A common junior mistake is creating a .env file locally but failing to update the .env.example file or documentation for the DevOps team.
# Junior mistake: Not declaring template variables
# Empty .env.example file
# Build script defaults to believing the variable always exists
npm run build
Why does it cause problems? Because in an automated process, the build server doesn't have access to your personal computer to get the .env file. It needs to be provided through the repo's Settings or Secret Management.
Comparison of Solutions:
- Quick fix: Commit the
.envfile directly to Git (Never, ever do this for security reasons!). Or manually type environment variables into the server every time a build fails. - Sustainable way:
- Always have a comprehensive
.env.examplefile with all keys (no values). - Use a validation script to check environment variables at the start of the build. If a critical variable is missing, fail the build immediately with a clear message: "MISSING API_URL VARIABLE".
- Harmonize variable naming across environments (Staging, UAT, Production).
- Always have a comprehensive
// Simple validation script in build process
const requiredEnv = ['VITE_API_URL', 'VITE_STRIPE_KEY'];
requiredEnv.forEach(key => {
if (!process.env[key]) {
console.error(`Error: Missing environment variable ${key}`);
process.exit(1);
}
});
Practical Lesson
Your code doesn't just live in the src folder. It lives in an entire ecosystem of build and deployment tools. Get into the habit of viewing the CI/CD process as part of your programming job, rather than something someone else does.
A good project is one where anyone new can successfully build after copying the .env.example file.
Notes on the transparency of configurations.
Series • Part 44 of 50