20

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?

Abdul Moeez
  • 1,331
  • 2
  • 13
  • 31
A Zarqam
  • 338
  • 2
  • 3
  • 12

7 Answers7

21

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.

Matt D. Webb
  • 3,216
  • 4
  • 29
  • 51
  • What is the risk if you save secret keys using this method? I thought the .env file was for that... – Alexis Aug 29 '21 at 23:25
  • @Alexis personally, I think it introduces some risk (albeit minor), that you leak secrets on the client. Here is a great blog post highlighting the potential risks: https://diogomonica.com/2017/03/27/why-you-shouldnt-use-env-variables-for-secret-data/ – Matt D. Webb Sep 23 '21 at 14:40
  • i would hardly call it a minor risk. if you bundle your app with client ids and secrets it would be VERY EASY for anyone on the internet to now act on your (your app's) behalf. its terrible practice and i would fire any dev on my team that did that – mlg87 Jun 02 '22 at 04:29
  • 1
    I see no "App Settings > Environment variables" in the Amplify console. – Audiopolis Sep 25 '22 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" – Matt D. Webb Sep 26 '22 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 03 '22 at 02:24
  • Genius @Audiopolis - I've been trying to figure this out for ages. How did you figure that out? I can't see anything documented? – JimmyTheCode Nov 08 '22 at 14:50
  • 1
    @JimmyTheCode There's a blue notice towards the top of this page: https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html My eyes/brain tends to skip those blue notices. – Audiopolis Nov 09 '22 at 03:46
  • @Audiopolis Haha mine too apparently! Thanks so much for pointing me to that – JimmyTheCode Nov 09 '22 at 06:34
14

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.

Carson Evans
  • 1,518
  • 1
  • 13
  • 12
  • 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 '21 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 '21 at 04:01
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.

DavidSinclair
  • 91
  • 1
  • 3
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.

leandro lavore
  • 151
  • 2
  • 5
  • 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 07 '20 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(),
});
atazmin
  • 4,757
  • 1
  • 32
  • 23