Search code examples
circleci

pass environment variable to node.js process in CircleCI


I am getting environment variables in CircleCI config.yml by using CircleCI context (Project Settings -> Environment Variables.

I am not able to pass them to node.js process process.env.SERVER_API. They are undefined.

I tried to them to pass it in config.yml:

docker:
      - image: circleci/node:14.9.0
        environment:
          SERVER_API: $SERVER_API

It doesn't work and I don't know how to pass them.

config.yml

version: 2.1
executors:
  node-executor:
    docker:
      - image: circleci/node:14.9.0
        environment:
          SERVER_API: $SERVER_API
commands:
  gatsby-build:
    steps:
      - checkout
      - restore_cache:
          keys:
            - yarn-cache-{{ checksum "yarn.lock" }}
      - run:
          name: Install Dependencies
          command: yarn install
      - save_cache:
          key: yarn-cache-{{ checksum "yarn.lock" }}
          paths:
            - ./node_modules
      - run:
          name: Gatsby Build
          command: yarn build
workflows:
  version: 2
  build-deploy:
    jobs:
      - release:
          filters:
            branches:
              only:
                - master
jobs:
  release:
    executor: node-executor
    working_directory: ~/tau-guide-website
    steps:
      - gatsby-build
      - run:
          name: Deploy
          command: |
            #upload all the code to machine
            scp -r -o StrictHostKeyChecking=no ~/tau-guide-website/public $PROJECT_FOLDER

Solution

  • The environment variables present during the Circle CI build are not passed to the deployed code, unless explicitly done. For my project I'm using available Circle CI env variable for the pipeline, but export them to .env file to include them in the final package. For the current code, I would:

    Remove this from image:

    environment: SERVER_API: $SERVER_API

    Add additional code to your build step:

          - run:
              name: Gatsby Build
              command: |
                touch .env.production
                echo "SERVER_API=$SERVER_API" > .env.production
                yarn build
    
    

    In case .env is not used at all, consider reading about dotenv package. You'll need to bring in dotenv as a dependancy and declare it in your files like so:

    require('dotenv').config({
      path: `.env.${process.env.NODE_ENV}`,
    })
    

    For our use case .env contains DB credentials and secrets as well, but is in .gitignore and generated during builds.