Notice: As an inspiration and starting point I have used Nader Dabit's Amplify React Workshop.
In this workshop we'll learn how to build web applications using AWS Amplify and React.
- AWS account
- Git on your computer & Github account
- Node.js 8 (or later) download here
- VS Code IDE (optional) download here
- Authentication
- GraphQL API with AWS AppSync
- Adding Authorization to the GraphQL API
- Serverless Functions
- REST API with a Lambda Function
- Adding Storage with Amazon S3
- Analytics
- Multiple Environments
- Deploying via the Amplify Console
- React Native
- Removing / Deleting Services
To get started, we first need to create a new React project & change into the new directory using the Create React App CLI.
If you already have this installed, skip to the next step. If not, either install the CLI & create the app or create a new app using npx:
npm install -g create-react-app create-react-app petsOr use npx (npm 5.2 & later) to create a new app:
npx create-react-app petsNow change into the new app directory & install the AWS Amplify & AWS Amplify React libraries:
cd pets npm install --save aws-amplify aws-amplify-react # or yarn add aws-amplify aws-amplify-reactLet's inspect what the command has created for us.
Try to run the app.
npm startNext, we'll install the AWS Amplify CLI:
npm install -g @aws-amplify/cliNow we need to configure the CLI with our credentials:
amplify configureIf you'd like to see a video walkthrough of this configuration process, click here.
Here we'll walk through the amplify configure setup. Once you've signed in to the AWS console, continue:
- Specify the AWS Region: eu-central-1
- Specify the username of the new IAM user: amplify-workshop-user
In the AWS Console, click Next: Permissions, Next: Tags, Next: Review, & Create User to create the new IAM user. Then, return to the command line & press Enter.
- Enter the access key of the newly created user:
accessKeyId: (<YOUR_ACCESS_KEY_ID>)
secretAccessKey: (<YOUR_SECRET_ACCESS_KEY>) - Profile Name: amplify-workshop-user
amplify init- Enter a name for the project: pets
- Enter a name for the environment: dev
- Choose your default editor: Visual Studio Code (or your default editor)
- Please choose the type of app that you're building javascript
- What javascript framework are you using react
- Source Directory Path: src
- Distribution Directory Path: build
- Build Command: npm run-script build
- Start Command: npm run-script start
- Do you want to use an AWS profile? Y
- Please choose the profile you want to use: amplify-workshop-user
Now, the AWS Amplify CLI has iniatilized a new project, let's review changed and added files. You will see a new folder: amplify & a new file called aws-exports.js in the src directory. These files hold your project configuration.
You can run
amplify statusto check the current status of our newly created amplify application.
To add authentication, we can use the following command:
amplify add auth- Do you want to use default authentication and security configuration? Default configuration
- How do you want users to be able to sign in when using your Cognito User Pool? Username
- Do you want to configure advanced settings? No, I am done
First, let's check the status of our applicaiton. Run
amplify statusNow, we'll run the push command and the cloud resources will be created in our AWS account.
amplify pushTo view the service you can run the console command the feature you'd like to view:
amplify console authNow, our resources are created & we can start using them!
The first thing we need to do is to configure our React application to be aware of our new AWS Amplify project. We can do this by referencing the auto-generated aws-exports.js file that is now in our src folder.
To configure the app, open src/index.js and add the following code below the last import:
import Amplify from 'aws-amplify' import config from './aws-exports' Amplify.configure(config)Now, our app is ready to start using our AWS services.
To add authentication, we'll go into src/App.js and first import the withAuthenticator HOC (Higher Order Component) from aws-amplify-react:
import { withAuthenticator } from 'aws-amplify-react'Next, we'll wrap our default export (the App component) with the withAuthenticator HOC:
export default withAuthenticator(App, { includeGreetings: true })# run the app npm startNow, we can run the app and see that an Authentication flow has been added in front of our App component. This flow gives users the ability to sign up & sign in.
To view the new user that was created in Cognito, go back to the dashboard at https://console.aws.amazon.com/cognito/. Also be sure that your region is set correctly.
We can access the user's info now that they are signed in by calling Auth.currentAuthenticatedUser().
import React, { useEffect } from 'react' import { Auth } from 'aws-amplify' function App() { useEffect(() => { Auth.currentAuthenticatedUser() .then(user => console.log({ user })) .catch(error => console.log({ error })) }) return ( <div className="App"> <p> Edit <code>src/App.js</code> and save to reload. </p> </div> ) } export default AppTo add a GraphQL API, we can use the following command:
amplify add apiAnswer the following questions
- Please select from one of the above mentioned services GraphQL
- Provide API name: PetsGraphQL
- Choose an authorization type for the API Cognito
- Do you want to configure advanced settings for the GraphQL API? No, I am done.
- Do you have an annotated GraphQL schema? N
- Do you want a guided schema creation? Y
- What best describes your project: Single object with fields (e.g. “Todo” with ID, name, breed)
- Do you want to edit the schema now? (Y/n) Y
When prompted, update the schema to the following:
type Pet @model { id: ID! name: String! breed: String! age: Int! }Again, let's check our application status:
amplify statusNext, let's push the configuration to our account:
amplify push- Do you want to generate code for your newly created GraphQL API Y
- Choose the code generation language target: javascript
- Enter the file name pattern of graphql queries, mutations and subscriptions: (src/graphql/**/*.js)
- Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? Y
- Enter maximum statement depth [increase from default if your schema is deeply nested] 2
To view the service you can run the console command the feature you'd like to view:
amplify console apiIn the AWS AppSync console, open your API & then click on Queries.
Execute the following mutation to create a new pet in the API:
mutation createPet { createPet(input: { name: "Miki" breed: "dachshund" age: 3 }) { id name breed age } }Now, let's query for the pet:
query listPets { listPets { items { id name breed age } } }We can even add search / filter capabilities when querying:
query listPets { listPets(filter: { age: { gt: 2 } }) { items { id name breed age } } }Now that the GraphQL API is created we can begin interacting with it!
The first thing we'll do is perform a query to fetch data from our API.
To do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.
Get code from here (assests/js/App-01.js) and paste it into src/App.js
Run the app with npm start and try it out.
Now, let's look at how we can create mutations. Let's change the component to use a useReducer hook.
New src/App.js code here (assests/js/App-02.js)
Let's create a second user and log in. OMG, other people can see my pets!
Quickly let's delete them within the web console with this mutation:
mutation deletePets { deletePet(input: { id: "<insert pet id here>" }), { id } }So far we enabled any logged in user to see any of the pets created. Next, let's make it so that pets can only be accessed by the user who created it.
To do so, we'll update the schema to add the following new type below the existing Pet type:
type Pet @model @auth(rules: [{allow: owner}]) { id: ID! name: String! breed: String! age: Int! }Next, we'll check and deploy the updates to our API:
amplify status amplify push- Do you want to update code for your updated GraphQL API: Y
- Do you want to generate GraphQL statements (queries, mutations and subscription) based on your schema types? Y
Now, the operations associated with this field will only be accessible by the creator of the item.
Let's check our lists of pets.
To add a serverless function, we can run the following command:
amplify add functionAnswer the following questions
- Provide a friendly name for your resource to be used as a label for this category in the project: breeds
- Provide the AWS Lambda function name: breeds
- Choose the function template that you want to use: Hello world function
- Do you want to access other resources created in this project from your Lambda function? No
- Do you want to edit the local lambda function now? Y
This should open the function package located at amplify/backend/function/breeds/src/index.js.
Edit the function to look like this (assets/js/breeds-lambda.js), and then save the file.
Next, we can test this out by running:
amplify function invoke breeds Using service: Lambda, provided by: awscloudformation
- Provide the name of the script file that contains your handler function: index.js
- Provide the name of the handler function to invoke: handler
You'll notice the output from Lambda function in your terminal.
Running "lambda_invoke:default" (lambda_invoke) task event: { key1: 'value1', key2: 'value2', key3: 'value3' } Success! Message: ------------------ {"statusCode":200,"body":["affenpinscher","african","airedale","akita","appenzeller","basenji","beagle","bluetick","borzoi","bouvier","boxer","brabancon","briard","chihuahua","chow","clumber","cockapoo","corgi","cotondetulear","dachshund","dalmatian","dhole","dingo","doberman","entlebucher","eskimo","germanshepherd","groenendael","husky","keeshond","kelpie","komondor","kuvasz","labrador","leonberg","lhasa","malamute","malinois","maltese","mexicanhairless","mix","newfoundland","otterhound","papillon","pekinese","pembroke","pitbull","pomeranian","pug","puggle","pyrenees","redbone","rottweiler","saluki","samoyed","schipperke","shiba","shihtzu","stbernard"]} Done. Done running invoke function.Where is the event data coming from? It is coming from the values located in event.json in the function folder (amplify/backend/function/basiclambda/src/event.json). If you update the values here, you can simulate data coming arguments the event.
Feel free to test out the function by updating event.json with data of your own.
Now let's push the function to the cloud:
amplify pushNow that we've created the a Lambda function let's add an API endpoint so we can invoke it via http.
To add the REST API, we can use the following command:
amplify add apiAnswer the following questions
- Please select from one of the above mentioned services REST
- Provide a friendly name for your resource that will be used to label this category in the project: breedsapi
- Provide a path (e.g., /items) /breeds
- Choose lambda source Use a Lambda function already added in the current Amplify project
- Choose the Lambda function to invoke by this path: breedsfunction
- Restrict API access Y
- Who should have access? Authenticated users only
- What kind of access do you want for Authenticated users read
- Do you want to add another path? (y/N) N
Now the resources have been created & configured & we can push them to our account:
amplify status amplify pushNow that the API is created we can start sending requests to it & interacting with it.
Let's request some data from the API:
Get new src/App.js code from here (assets/js/App-03.js).
Let's try it!
To add storage, we can use the following command:
amplify add storageAnswer the following questions
- Please select from one of the below mentioned services Content (Images, audio, video, etc.)
- Please provide a friendly name for your resource that will be used to label this category in the project: pets
- Please provide bucket name: YOURUNIQUEBUCKETNAME
- Who should have access: Auth users only
- What kind of access do you want for Authenticated users create/update, read, delete
amplify status amplify pushNow, storage is configured & ready to use.
What we've done above is created and configured an Amazon S3 bucket that we can now start using for storing items.
Here are some examples on how we could interact with storage:
import { Storage } from 'aws-amplify' // create function to work with Storage function addToStorage() { await Storage.put('text/MyPetDiary.txt', ` My pet is awesome. `) console.log('data stored in S3!') } // add click handler <button onClick={addToStorage}>Add To Storage</button>This would create a folder called text in our S3 bucket & store a file called MyPetDiary.txt there with the code we specified in the second argument of Storage.put.
To view the new bucket that was created in S3, go to the dashboard at https://console.aws.amazon.com/s3. Also be sure that your region is set correctly.
If we want to read everything from this folder, we can use Storage.list:
readFromStorage() { const data = Storage.list('text/') console.log('data from S3: ', data) }If we only want to read the single file, we can use Storage.get:
readFromStorage() { const data = Storage.get('text/MyPetDiary.txt') console.log('data from S3: ', data) }If we wanted to pull down everything, we can use Storage.list:
function readFromStorage() { const data = Storage.list('') console.log('data from S3: ', data) }Here's how you can store an image:
function App() { async function onChange(e) { const file = e.target.files[0]; await Storage.put('example.png', file) console.log('image successfully stored!') } return ( <input type="file" accept='image' onChange={(e) => this.onChange(e)} /> ) }Here's how you can read and display an image:
import React, { useState } from 'react' function App() { const [imageUrl, updateImage] = useState('') async function fetchImage() { const imagePath = await Storage.get('example.png') updateImage(imagePath) } return ( <div> <img src={imageUrl} /> <button onClick={fetchImage}>Fetch Image</button> </div> ) }We will now use the S3Album component, one of a few components in the AWS Amplify React library to create a pre-configured photo picker:
import { S3Album, withAuthenticator } from 'aws-amplify-react' // ... { state.pets.map((p, i) => ( <div key={i}> <h2>{p.name}</h2> <h4>{p.age}</h4> <p>{p.description}</p> <div> <S3Album level="private" path={`/${p.name}`} picker pickerTitle={`Upload ${p.name}'s photos`} /> </div> </div> )) } // ...Complete src/App.js code is available here (assets/js/App-04.js).
To add analytics, we can use the following command:
amplify add analyticsNext, we'll be prompted for the following:
- Provide your pinpoint resource name: amplifyanalytics
- Apps need authorization to send analytics events. Do you want to allow guest/unauthenticated users to send analytics events (recommended when getting started)? Y
- overwrite YOURFILEPATH-cloudformation-template.yml Y
Now that the service has been created we can now begin recording events.
To record analytics events, we need to import the Analytics class from Amplify & then call Analytics.record:
import { Analytics } from 'aws-amplify' state = {username: ''} async componentDidMount() { try { const user = await Auth.currentAuthenticatedUser() this.setState({ username: user.username }) } catch (err) { console.log('error getting user: ', err) } } recordEvent = () => { Analytics.record({ name: 'My test event', attributes: { username: this.state.username } }) } <button onClick={this.recordEvent}>Record Event</button>You can create multiple environments for your application in which to create & test out new features without affecting the main environment which you are working on.
When you create a new environment from an existing environment, you are given a copy of the entire backend application stack from the original project. When you make changes in the new environment, you are then able to test these new changes in the new environment & merge only the changes that have been made since the new environment was created back into the original environment.
Let's take a look at how to create a new environment. In this new environment, we'll re-configure the GraphQL Schema to have another field for the pet rank.
First, we'll initialize a new environment using amplify env add:
amplify env add > Do you want to use an existing environment? No > Enter a name for the environment: adddesc > Do you want to use an AWS profile? Y > Please choose the profile you want to use: amplify-workshop-profileOnce the new environment is initialized, we should be able to see some information about our environment setup by running:
amplify env list | Environments | | ------------ | | dev | | *adddesc |Now we can update the GraphQL Schema in amplify/backend/api/CryptoGraphQL/schema.graphql to the following (adding the rank field):
type Pet @model @auth(rules: [{allow: owner}]) { id: ID! name: String! breed: String! age: Int! description: String! }And update our src/App.js with the code from here (assets/js/App-05.js)
Now, we can create this new stack by running amplify push:
amplify pushAfter we test it out, we can now merge it into our original local environment:
amplify env checkout localNext, run the status command:
amplify statusYou should now see an Update operation.
To deploy the changes, run the push command:
amplify push- Do you want to update code for your updated GraphQL API? Y
- Do you want to generate GraphQL statements? Y
Now, the changes have been deployed & we can delete the adddesc environment:
amplify env remove adddesc Do you also want to remove all the resources of the environment from the cloud? YNow, we should be able to run the list command & see only our main environment:
amplify env list(re:Invent 2019 launch)[https://aws.amazon.com/blogs/aws/amplify-datastore-simplify-development-of-offline-apps-with-graphql/]
For hosting, we can use the Amplify Console to deploy the application.
The first thing we need to do is create a new GitHub repo for this project. Once we've created the repo, we'll copy the URL for the project to the clipboard & initialize git in our local project:
git init git remote add origin git@github.com:username/project-name.git git add . git commit -m 'initial commit' git push origin masterNext we'll visit the Amplify Console in our AWS account at https://eu-west-1.console.aws.amazon.com/amplify/home.
Here, we'll click Get Started to create a new deployment. Next, authorize Github as the repository service.
Next, we'll choose the new repository & branch for the project we just created & click Next.
In the next screen, we'll create a new role & use this role to allow the Amplify Console to deploy these resources & click Next.
Finally, we can click Save and Deploy to deploy our application!
Now, we can push updates to Master to update our application.
AWS Amplify also has framework support for React Native.
To get started with using AWS Amplify with React Native, we'll need to install the AWS Amplify React Native package & then link the dependencies.
npm install aws-amplify-react-native # If using Expo, you do not need to link these two libraries as they are both part of the Expo SDK. react-native link amazon-cognito-identity-js react-native link react-native-vector-iconsImplementing features with AWS Amplify in React Native is the same as the features implemented in the other steps of this workshop. The only difference is that you will be working with React Native primitives vs HTML elements.
If at any time, or at the end of this workshop, you would like to delete a service from your project & your account, you can do this by running the amplify remove command:
amplify remove auth amplify pushIf you are unsure of what services you have enabled at any time, you can run the amplify status command:
amplify statusamplify status will give you the list of resources that are currently enabled in your app.
amplify delete