I am building a react app using create-react-app
, which uses the javascript aws sdk to connect to dynamodb. I have it working locally, however I am unable to get this to work when hosted on AWS Amplify. My sticking point is I don't know how to pass aws_access_key_id and aws_secret_access_key in Amplify to the react app.
Locally, I have a .env file with REACT_APP_AWS_ACCESS_KEY_ID
and REACT_APP_AWS_SECRET_ACCESS_KEY
. These of course are not defined in Amplify.
Inside package.json, I tried to set the variables in the build script. I even tried just with the access_key_id alone to rule out issues in setting two variables at once.
"scripts": {
"build": "REACT_APP_AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID REACT_APP_AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY react-scripts build",
},
However, this results in an empty value for the REACT_APP_ variables.
I tried modifying the Amplify app build settings in two different ways both with and without the package.json change, also with no luck.
build:
commands:
- npm run build
- echo "REACT_APP_AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID" >> .env
build:
commands:
- npm run build
- echo "REACT_APP_AWS_ACCESS_KEY_ID=$REACT_APP_AWS_ACCESS_KEY_ID" >> .env
I don't know what else I can do or if I'm completely on the wrong track. I was pretty sure that the AWS environment injects these when the app is run within the ecosystem, because I've seen it work with a different app hosted on Elastic Beanstalk.
Ultimately all I need is the access_key_id and the secret_access_key for use in the javascript aws sdk to initialize the dynamodb client like such.
const client = new DynamoDB({
region: 'us-east-1',
credentials: {
accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.REACT_APP_AWS_SECRET_ACCESS_KEY
}
});
CodePudding user response:
You need to set env vars in the amplify console if you want amplify to have build-time access to them.
I am sure you know this, but it is almost always a Very Bad Idea to include your aws credentials in your react client bundle in this way. Your plaintext secrets will be readable by all your web users.
As Aws reminds us: Storing sensitive values, such as API keys, inside these frontend framework prefixed environment variables is not a best practice and is highly discouraged