23

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?

7 Answers 7

25

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.

9
  • What is the risk if you save secret keys using this method? I thought the .env file was for that...
    – Alexis
    Aug 29, 2021 at 23:25
  • 1
    I see no "App Settings > Environment variables" in the Amplify console.
    – Audiopolis
    Sep 25, 2022 at 22:09
  • 1
    @Audiopolis are you sure you're in AWS Amplify? Make sure to select an app, then the left menu there is "App Settings" and "Environment variables" Sep 26, 2022 at 16:25
  • 1
    The problem was that you can only set environment variables for apps connected to a GitHub repo. I was manually pushing, so the app's build process was outside the control of Amplify.
    – Audiopolis
    Oct 3, 2022 at 2:24
  • 1
    @JimmyTheCode There's a blue notice towards the top of this page: docs.aws.amazon.com/amplify/latest/userguide/… My eyes/brain tends to skip those blue notices.
    – Audiopolis
    Nov 9, 2022 at 3:46
15

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.

3
  • 2
    Nice. For some reason, instructions in AWS page are unclear. They ask to add a :$BUILD_END, the order is reversed, and the file is /backend/.env...
    – Alexis
    Aug 29, 2021 at 23:25
  • This is what I need. I searched all over stack overflow and find you. This answer should definetly have more than 3 votes.
    – Pablo LION
    Sep 26, 2021 at 4:01
  • Great answer. This worked for me.
    – Han
    Nov 22 at 13:13
9

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.

7

@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.

1
  • 1
    Thanks for sharing, i have uploaded my files with a zip file and it worked. i will remember your answer for the next try, cheers
    – A Zarqam
    Oct 7, 2020 at 15:27
3

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.

2

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

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(),
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.