Troubleshooting Environment Variables with Vite and Docker
TL;DR
- Understand Vite reads client-side environment variables at build-time.
- Ensure Docker builds have access to necessary
.envvariables. - GitLab CI/CD pipelines need explicit declaration of environment variables.
- Non-secret variables can be included in the build process as plain text.
Working with environment variables can often feel like a maze, especially when they need to be configured across multiple technologies and platforms. Today, I dove deep into figuring out why my client-side environment variables weren’t showing up as expected in my React app using Remix with Vite and Docker.
Environment Variables & Vite
Vite, the build tool I’m using, pulls client-facing environment variables during build time, not runtime. This is key because there’s no runtime environment for Vite on the client-side. My initial hurdle was seeing undefined variables in my app, indicating they weren’t available during the build in the Docker container.
Docker Configuration
To solve this, I included the VEET-prefixed environment variables in my Dockerfile:
-
Declared them as ARG:
1ARG VITE_CLIENT_PROXY_URL -
Set them with ENV to bake into the client code:
1ENV VITE_CLIENT_PROXY_URL=${VITE_CLIENT_PROXY_URL}
Yet, even after this setup, when deployed, variables showed up as blank strings, hinting they weren’t correctly populated during the build.
Fine-tuning with GitLab CI/CD
Realizing I couldn’t pass environment variables directly into Docker on Railway, I shifted focus to GitLab CI, our continuous integration tool. Here’s the plan:
-
Environment Variables: Extract all
VITEenvironment variables from.envand declare them ingitlab-ci.ymlas plain text. They aren’t sensitive since they are part of the frontend code. -
Pass through CI/CD: Ensure these variables are explicitly passed into both the
Dockerfileand the build process:1 2 3 4variables: VITE_CLIENT_PROXY_PORT: "yourValueHere" VITE_CLIENT_PROXY_URL: "yourValueHere" # more VITE variables... -
Re-deploy and Test: Sync changes and redeploy to ensure they are available. Double-check in the console for empty strings.
Conclusion
The main takeaway is ensuring your environment variables are properly set up across your tooling and continuous deployment pipelines. By understanding where and how Vite gets its build-time variables and configuring Docker and GitLab CI accordingly, I’m set to avoid blank strings and have a consistent deployment strategy going forward.
ryer.io