How to add environment variables to AWS amplify?

26.3k views Asked by At

I have a React/Node app which i am trying to host on AWS amplify. first try, my app deployed but i saw some pages are not loading due to lack of the environment variables. i have added them to the AWS console before deploying and it did not work. then i did some search and i saw that i need to modify "amplify.yml" file to:

build:
  commands:
    - npm run build:$BUILD_ENV

but not only it did not work, also the app is not working anymore. any ideas?

8

There are 8 answers

1
leandro lavore On

@A Zarqam Hey man, I ran into this issue ans spent a decent amount of time on it. What worked for me was:

On my React code, use process.env.VARIABLE_NAME

On my webpack.config.js use the following plug-in:

new webpack.EnvironmentPlugin(['VARIABLE_NAME_1', 'VARIABLE_NAME_2'])

On the Amplify environment variables put the VARIABLE_NAME_1,etc and then the values, just like in the docs says.

Last on the build settings:

build:
      commands:
        - npm run build
        - VARIABLE_NAME_1=$VARIABLE_NAME_1 

(the one with $ is a reference to the one you put in amplify. Also I think you must have no spaces between the = symbol)

Then trigger a build, and cross your fingers.

9
Matt D. Webb On

As this question specifically references React, here are the steps you need to use environment variables in your React based application in AWS Amplify.

In your client-side JS:

const BUILD_ENV = process.env.REACT_APP_BUILD_ENV || "any-default-local-build_env"; 

The key thing to note here is my pre-fix of REACT_APP_ which is covered the Create-React-App docs: here

Now, in your Amplify console, under App Settings > Environment variables:

![enter image description here

Finally, you also need to add this reference under App Settings > Build Settings:

enter image description here

Note: "BUILD_ENV" can be any string you wish. Within the environment variables you can provide the necessary DEV / PROD overrides.

DO NOT store SECRET KEYS using this method, AWS provide a secrets manager for this. This method is for publishable keys, like connecting to Firebase or Stripe and the key is fine to be public.

0
DavidSinclair On

To get @leandro's answer working I had to wrap the AWS environment variable names in curly braces:

build:
  commands:
    - npm run build
    - VARIABLE_NAME_1=${VARIABLE_NAME_1}

Probably better as a comment but I don't have enough points to post one.

0
Ashton Pierce On

An add on to @leandro's for anyone checking for this in the future I just want to simplify what you need to do since I was completely lost on this:

  1. In your code reference all API keys as process.env.EXAMPLE_API_KEY_1
  2. Run this in your root folder terminal npm install react-app-rewired --save-dev
  3. Add config-overrides.js to the project root directory.(NOT ./src)
// config-overrides.js
module.exports = function override(config, env) {
    // New config, e.g. config.plugins.push...
    return config
}
  1. Set your variables in AWS Amplify with your key and variable, pretty self-explanatory.
  2. In your build settings make it look something like this
    (I personally don't add npm build in here but you can if you need to.)
frontend:
 phases:
   build:
     commands:
           - EXAMPLE_API_KEY_1=${EXAMPLE_API_KEY_1}
           - EXAMPLE_API_KEY_2=${EXAMPLE_API_KEY_2}

  1. Start or restart your build.

I used @leandro's answer and mixed in an answer from this question to get it to work for me.

0
atazmin On

This worked for me to deploy React to Amplify

amplify.yml

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm install
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

enter image description here in App.js

const client = new ApolloClient({
  uri:
    process.env.NODE_ENV !== 'production'
      ? 'http://localhost:1337/graphql'
      : process.env.REACT_APP_ENDPOINT,
  cache: new InMemoryCache(),
});
3
Carson Evans On

The Amplify documentation on Environmental Variables has a section on "Accessing Environmental Variables".

Per that documentation, in your Amplify.yml (either in the console or by downloading it to the root of your project), you can use a command to push Amplify Environmental Variables into your .env. If you created an Environmental Variable in Amplify called "REACT_APP_TEST_VARIABLE" you would do...

   build:
      commands:
        - echo "REACT_APP_TEST_VARIABLE=$REACT_APP_TEST_VARIABLE" >> .env
        - npm run build

Once in your .env you can access them through process.env...

console.log('REACT_APP_TEST_VARIABLE', process.env.REACT_APP_TEST_VARIABLE)

If you are using Create React App, you already have dotenv, or see Adding an .env file to React Project for more info.

Obligatory reminder to add your .env to your .gitignore, and don't store anything in .env that is sensitive.

0
Akshay Bhanderi On

This is how I did it. :)

Setting up the different values of same env variable in different amplify envs: enter image description here

Build settings:

version: 1
backend:
  phases:
    build:
      commands:
        - '# Execute Amplify CLI with the helper script'
        - amplifyPush --simple
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - REACT_APP_BUILD_ENV=${REACT_APP_BUILD_ENV}
        - npm run build
  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

Access the same env var in react js web app:

export const ENV = process.env.REACT_APP_BUILD_ENV ?? "dev";
console.log("BRANCH: ", ENV)

Logs can be found on the browser console: enter image description here enter image description here

0
Lucas Antunes On

Just to add to other comments regarding Secret keys, since SO doesn't let me comment until 50 rep... If you're not using those Env Variables in your front-end app such as process.env.<var_name>, and only use them during build time, you're fine. Those files will not be bundled into your front-end app.

I know this question is related to frontend apps but its title appeared in search engines for me even though I was looking for build variables only, so it might be useful for other people too.