CodexBloom - Programming Q&A Platform

How to manage different builds for staging and production in a React app using CI/CD?

👀 Views: 178 💬 Answers: 1 📅 Created: 2025-10-17
reactjs ci-cd github-actions JavaScript

I'm sure I'm missing something obvious here, but I need help solving Currently developing a React application that leverages a CI/CD pipeline for deployment. The goal is to differentiate between staging and production builds, ensuring that particular environment variables and configuration settings are applied correctly during these deployments. I’ve set up environment variables using a `.env` file, but I’m having trouble configuring the pipeline to switch between these environments effectively. For instance, my `.env.production` file contains sensitive API keys and the production URL, while the `.env.staging` file is set up for testing purposes with a different API and URL. Here's a snippet of my `.env` files: ```plaintext # .env.production REACT_APP_API_URL=https://api.myapp.com REACT_APP_API_KEY=prod-secret-key ``` ```plaintext # .env.staging REACT_APP_API_URL=https://staging.api.myapp.com REACT_APP_API_KEY=staging-secret-key ``` In my CI/CD configuration using GitHub Actions, I’ve set the following steps in my workflow file: ```yaml name: CI/CD Pipeline on: push: branches: - main jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Node.js uses: actions/setup-node@v2 with: node-version: '14' - name: Install dependencies run: npm install - name: Build for production run: npm run build --if-present env: NODE_ENV: production - name: Build for staging run: npm run build --if-present env: NODE_ENV: staging ``` Despite this setup, I find that the production build isn't picking up the correct variables from the `.env.production` file consistently. I’ve run `npm run build` directly on my local machine and confirmed that it works fine, but the CI/CD pipeline appears to ignore these files. What am I missing? Is there a better way to handle these configurations in a CI/CD environment? Any tips on how to ensure that the correct environment variables are utilized in builds would be greatly appreciated. My team is using Javascript for this microservice. Thanks in advance! My team is using Javascript for this service.