I am using GitLab CI/CD to deploy my React application (built with Vite) to Firebase Hosting. However, I’m facing an issue where the environment variables I pass during deployment are not being set correctly, and they show up as undefined when I access the site after a successful deployment.
Problem: When the CI/CD pipeline completes successfully, I open the deployed site, and none of the environment variables are being passed properly—they all appear as undefined.
gitlab-ci.yml
image: node:18
stages:
- build_and_deploy
variables:
VITE_ENVIRONMENT: $VITE_ENVIRONMENT
VITE_ANALYTICAL_URL_PRODUCTION: $VITE_ANALYTICAL_URL_PRODUCTION
VITE_ANALYTICAL_URL_DEVELOPMENT: $VITE_ANALYTICAL_URL_DEVELOPMENT
VITE_DOCRETR_URL_DEVELOPMENT: $VITE_DOCRETR_URL_DEVELOPMENT
VITE_DOCRETR_API_KEY_DEVELOPMENT: $VITE_DOCRETR_API_KEY_DEVELOPMENT
VITE_KRONOS_URL_PRODUCTION: $VITE_KRONOS_URL_PRODUCTION
VITE_KRONOS_URL_DEVELOPMENT: $VITE_KRONOS_URL_DEVELOPMENT
VITE_KRONOS_API_KEY_PRODUCTION: $VITE_KRONOS_API_KEY_PRODUCTION
VITE_KRONOS_API_KEY_DEVELOPMENT: $VITE_KRONOS_API_KEY_DEVELOPMENT
FIREBASE_TOKEN: $FIREBASE_TOKEN
build_and_deploy:
stage: build_and_deploy
script:
# Check if environment variables are set correctly
- echo $VITE_KRONOS_API_KEY_DEVELOPMENT
# Install dependencies and build the project
- npm install
- npm run build
# Install Firebase CLI
- npm install -g firebase-tools
# Deploy to Firebase using the Firebase token
- echo "Deploying to Firebase with token $FIREBASE_TOKEN"
- firebase deploy --only hosting --token $FIREBASE_TOKEN --project sop-generator
only:
- main # Run only on the 'main' branch
All the variables shown except for the $FIREBASE_TOKEN are visible, not protected or masked and expanded
Only the $FIREBASE_TOKEN is protected, masked and expanded.
Could you please help me pass the env variables to firebase deploy somehow?
The problem is that Vite does not inject environment variables at runtime; it statically embeds them during the build process.
I suggest creating a .env
file before running npm run build
, like this:
- echo $VITE_KRONOS_API_KEY_DEVELOPMENT
- |
echo "VITE_ENVIRONMENT=$VITE_ENVIRONMENT" > .env
echo "VITE_ANALYTICAL_URL_PRODUCTION=$VITE_ANALYTICAL_URL_PRODUCTION" >> .env
echo "VITE_ANALYTICAL_URL_DEVELOPMENT=$VITE_ANALYTICAL_URL_DEVELOPMENT" >> .env
echo "VITE_DOCRETR_URL_DEVELOPMENT=$VITE_DOCRETR_URL_DEVELOPMENT" >> .env
echo "VITE_DOCRETR_API_KEY_DEVELOPMENT=$VITE_DOCRETR_API_KEY_DEVELOPMENT" >> .env
echo "VITE_KRONOS_URL_PRODUCTION=$VITE_KRONOS_URL_PRODUCTION" >> .env
echo "VITE_KRONOS_URL_DEVELOPMENT=$VITE_KRONOS_URL_DEVELOPMENT" >> .env
echo "VITE_KRONOS_API_KEY_PRODUCTION=$VITE_KRONOS_API_KEY_PRODUCTION" >> .env
echo "VITE_KRONOS_API_KEY_DEVELOPMENT=$VITE_KRONOS_API_KEY_DEVELOPMENT" >> .env