How to pass environment variables from AWS CodeBuild to React.js frontend application

This story will guide you on how to set build-time environment variables via CodeBuild for your React.js application.

Stephen Lee (Sungsoo)
2 min readDec 8, 2022

Aite, enough. let’s jump straight to it.

Prerequisites

  • Should have a React.js application configured via create-react-app. i.e. npx create-react-app my-app --template typescript.
  • Should have an AWS account.
  • Should have CodeBuild configured in AWS and have buildspec.yml file in your project folder. Mine looks like this (github).

Let’s get started

Set environment variables in CodeBuild project.

i.e. https://us-east-1.console.aws.amazon.com/codesuite/codebuild/projects/[YOUR_PROJECT]/edit/environment?region=us-east-1

There are 3 types of environment variables: Plaintext, Parameter, and Secrets Manager. I chose to use Parameter (a.k.a. Systems Manager Parameter) for all the API keys or credentials so that they don’t show them in logs during CodeBuild unlike Plaintext. AWS accounts with permissions to Systems Manager Parameter Store will have access to them. If you want to be more secured and restrictive, you can opt to use Secrets Manager. You can read more about them here.

Configure your buildspec.yml to set .env variables

# ...
pre_build:
commands:
# export the env variables
- echo REACT_APP_ENV=${ENV} >> .env
- echo REACT_APP_FIREBASE_API_KEY=${FIREBASE_API_KEY} >> .env
- echo REACT_APP_FIREBASE_AUTH_DOMAIN=${FIREBASE_AUTH_DOMAIN} >> .env
- echo REACT_APP_FIREBASE_PROJECT_ID=${FIREBASE_PROJECT_ID} >> .env
- echo REACT_APP_FIREBASE_STORAGE_BUCKET=${FIREBASE_STORAGE_BUCKET} >> .env
- echo REACT_APP_FIREBASE_SENDER_ID=${FIREBASE_SENDER_ID} >> .env
- echo REACT_APP_FIREBASE_APP_ID=${FIREBASE_APP_ID} >> .env
- echo REACT_APP_FIREBASE_MEASUREMENT_ID=${FIREBASE_MEASUREMENT_ID} >> .env
# install dependencies
- echo installing dependencies...
- yarn install
# ...

You need to prefix the environment variables to REACT_APP_* because of the way create-react-app is set up (reference). echo hello >> .env will write hello string in the nextline in .env file. Then, all the REACT_APP_* variables will be ready to be used during runtime.

You can check out my buildspec.yml.

Use the variables anywhere in your app

const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
getAnalytics(app);

That’s it! Happy coding!

Live life to the fullest,

Stephen S. Lee

--

--