且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将环境变量添加到 AWS 放大?

更新时间:2023-11-24 22:19:16

由于这个问题特别提到了 React,以下是您需要在 的基于 React 的应用程序中使用环境变量的步骤AWS Amplify.

在您的客户端 JS 中:

const BUILD_ENV = process.env.REACT_APP_BUILD_ENV ||任何默认本地构建环境";

这里要注意的关键是我的 REACT_APP_ 前缀,它包含在 Create-React-App 文档中:

最后,你还需要在App Settings下添加这个引用>构建设置:

注意:BUILD_ENV"可以是任何你想要的字符串.在环境变量中,您可以提供必要的 DEV/PROD 覆盖.

请勿使用此方法存储 SECRET KEYS,AWS 提供 秘密经理.此方法适用于可发布的密钥,例如连接到 Firebase 或 Stripe,并且密钥可以公开.

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?

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:

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

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.