reactjsenvironment-variablesvitecicd

Configuring .env files on server (react CI/CD)


I'm using react with vite and I have several .env files like .env.production, .env.qa etc with different configurations. I've read that it's not safe to push them and better to keep in .gitignore. Everything works fine locally. But how do i get those files during build process? Currently I'm getting error 'Failed to find .env file at path'. Do i have to manually upload the .env files on server? Or do i have to use gitlab CI/CD variables? (which doesn't work for me since some of my values are shorter than needed). I'm having a hard time understanding how everything works.


Solution

  • I won't suggest to manually upload .env Files on the server.

    Instead you can manage environment-specific configuration files outside the repository and use an automated deployment tool (like Ansible, Terraform, etc.) to place these files in the correct location on the server before the build.

    Another way is you can generate the .env file dynamically from variables defined in GitLab CI/CD settings. But GitLab has a limitation that prevents masking variables with fewer than 8 characters, like in your case.

    In that case you can work around this by disabling the logging of commands to prevent exposing the values like below :

    build:
      stage: build
      script:
        # Disable command echo to avoid logging variable values
        - set +x
        # Generate the .env file dynamically using GitLab variables
        - echo "VITE_API_URL=${VITE_API_URL}" >> .env
        - echo "VITE_APP_SECRET=${VITE_APP_SECRET}" >> .env
        # Re-enable command echo after sensitive commands
        - set -x
    

    In above example: