Creating React + GraphQL Serverless Web application using AWS Amplify | by Janitha Tennakoon | Towards Data Science

AWS Amplify is a service provided by Amazon Web Services where it gives the ability to create end to end solutions for mobile and web platforms with a more secure and scalable way using AWS services. AWS Amplify was initially launched in November 2018 and since then many developers have created and deployed their new applications to Amplify because of the simplicity and reliability provided by Amplify.
Amplify provides easy to configure features with it called modules named authentication, storage, backend API, and hosting and deployments, etc. You can get more information about the modules provided by the Amplify from here. In this article, we are going to use 3 modules, authentication, backend api, and the hosting and deployment.
In this article let’s try to build and deploy a react application with a GraphQL api. Below are tasks that we are going to perform in this article in order to achieve our goal.
Install and configure Amplify CLI
Create react application
Add authentication
Add GraphQL api
Deploy and host on Amplify
The full react application code that I am using for the article can be found here.
The first step we need to do before creating our react application is that we need to install the Amplify CLI tool globally in our system. For that, we need to run the following command in the terminal. (we need node.js installed in our system to use npm)
npm install -g @aws-amplify/cli
Now in order to configure the installed Amplify with our AWS account issue the below command.
amplify configure
This will prompt a series of questions that we need to answer. First, it will ask us to log in to our AWS account using the web console. The next important question is the IAM user that it will create for our Amplify CLI tool. After specifying a name for the user it will again redirect us to the IAM console where we need to provide necessary permission policies for our user.
Here make sure to add AdministratorAccess policy to the user. Then go to Security credentials tab and create an access key for this user and remember to download and store credential details. Back in the console as next steps, it will ask for this accessKeyId and secretAccessKey. Now our configuration for Amplify CLI is done.
Now let’s start creating our react application. For the creation of a new react application issue the following commands.
npx create-react-app amplify-react-samplecd amplify-react-samplenpm start
If everything went smoothly in localhost:3000 it should show the newly created react application.
The next step is to add aws-amplify to our react application as a dependency. This package will have the functionality of doing all the configurations on Amplify from our react code.
npm install aws-amplify @aws-amplify/ui-react
Next, let’s initialize an Amplify project for our react application.
amplify init
Again we will be prompted to answer a series of questions. For the project name, you can give any name you want. For the type of application select javascript and for the framework select react. For other questions, we can leave the default values since we are not going to change the react build and run scripts inside our application.
The following modifications in our project will be done during this step.
A new folder named amplify will be created at the root level of the project. This stores every configuration related to our backend (AWS resources). (In this article we are going to add authentication and GraphQL API). As we add more amplify features configurations related to those features will be stored inside this folder as Infrastructure As code.
a file called aws-exports.js will be created in the src directory that holds all the configuration for the services that we will create with Amplify. For now, it only contains region information because we are still not using any Amplify services.
At the same time on AWS a cloud project will be created which we can access through the Amplify console. The console also gives some other additional configuration options as well for our application.
Now our react application is initialized with Amplify and let’s move to the next task, adding authentication.
For authentication, Amplify uses AWS Cognito as the main authentication provider. AWS Cognito provides many features like authentication, user registration, account recovery, and many more. You can check more available features or Cognito from here. To add Cognito authentication on our application issue the below command in the terminal.
amplify add auth
Again we will be prompted with questions for our authentication configurations. For this article, we will choose the default configuration for security configuration. (if we want we can update this later by running amplify update auth). For the sign-in option, you can choose either username or email.
That’s it, now we have our authentication module created for us. But before testing it in our application we need to push this configuration to Amplify. To do that simply issue the following command in the terminal.
amplify push
This command will create the required configurations on Amplify and Cognito on AWS and will also edit our aws-exports.js file with Cognito auth configurations.
The next step is to use this Cognito authentication in our react application. For that first, we need to import the Amplify module for our application. Edit index.js file to import Amplify and configure Amplify module using the configurations in aws-exports.jsfile.
import Amplify from 'aws-amplify';import awsconfig from './aws-exports'; Amplify.configure(awsconfig);
Now we can use the auth module in our application. Go to app.jsand first import the below modules.
import { withAuthenticator, AmplifySignOut } from "@aws-amplify/ui-react";
Next, wrap our App component with WithAuthenticator. Here AmplifySignOut is a component provided by amplify-react where it acts as a signout button. For more pre-built UI components offered by Amplify, you can check here.
Now that we have added the Amplify authentication in our react application let’s start the server and test whether it works. Run npm start and go to the browser.
Now it should display a sign-in page when we try to access localhost:3000. If you can see the above page that means our authentication is set correctly. The next step would be to create a user in our Cognito user pool. You can either create a user through the IAM console or by clicking on Create account. Users can be managed through the Cognito console as well.
Now try to login using the user we created and should now be able to go to our home page.IF everything works just fine let’s move to the next task.
Amplify supports creating serverless backend APIs using AWS AppSync. AppSync supports both REST and GraphQL API frameworks. For this article, we are going to use AppSync GraphQL api. To learn more about what is GraphQL and how to create a serverless GraphQL using AWS AppSync you can check out this article written by me.
Before adding our backend GraphQL api let’s do some modifications on our react application for showing data in a table. In this article Let’s assume our application will show data related to actors.
In the above code, I am using material-ui for the creation of the table which you can install using npm install @material-ui/core . The code only displays a table where for now we have defined a set of data inside getActors() method. (Make sure to import the Home component in App.js as well)
Now rather than taking hard coded values inside the code, let’s try to create our own GraphQL API to retrieve actor information from the api. To add a GraphQL api to our application simply issue the following command in the terminal.
amplify add api
For the questions you will be asked to provide select service as GraphQL and for authorization choose Amazon Cognito User Pool. Next for the schema template select Single object with fields. This will automatically create a simple GraphQL schema for us. Next when you asked to edit the schema press Y.
This will open our schema.graphql which is created automatically. There we can see the schema with model Todo already created.
type Todo @model {  id: ID!  name: String!  description: String}
let’s edit this schema for our use case where our model will be Actors.
Here if we need we can also specify the Query and Mutation that is allowed in our schema. In GraphQL Query is like a GET call where we do not do any modifications to the data and Mutation is like PUT, POST, DELETE calls where we do modifications on the data. But this can be automatically generated in AppSync if we want as well when we push the api.
The next step is to push this GraphQL api to Amplify where it will be get created on AppSync. Issue below command to push the API.
amplify push
Here again, a set of configurations will be asked from us. Select the language target to be javascript and make file pattern the default. Later it will ask to generate all GraphQL operations for our schema. Make sure to enter Yes for this as this will auto-generate Query and Mutation for our Actor model.
This will create our GraphQL API on AppSync. Our database will also get automatically created on AWS DynamoDB. Also, it creates a new folder inside the amplify folder named backend. Our Actor schema and other AppSync related configurations can be found inside this backend folder.
At the end of the configuration, we will be provided with the GraphQL endpoint which we configured using actors schema. Now if we go to the AppSync console we can see the newly created Actors api.
Now you can see that our schema is updated with Query and Mutation since AppSync generated those for us. Here let’s try to create some data so we can query from the API. Go to Queries tab. There, from the dropdown select Mutation and click on the + button.
Mutation is how we can do updates in our database. Since we need to create actor click on createActor and fill with Actor details. For now, let’s add two actors.
Now let’s test our GraphQL. For that, we need to use a Query. Remove Mutation and add Query by clicking on + button
Let’s do a Query using listActors by returning only id, firstName, lastName, age, and movies fields.
If the correct results are returning from our Query that means our GraphQL api is now properly configured. Now let’s start adding the GraphQL API to our react application.
First, we need to import Amplify, API, graphqlOperation modules in our Home component.
import Amplify, { API, graphqlOperation } from 'aws-amplify'
Next, we need to import Query and Mutation we are going to perform in the application. In our case Query is listActors and Mutation is createActor. We can get these Query or Mutation from either AppSync console or in the aws-schema.graphql file inside backend/api folder
import { createActor} from './graphql/mutations' import { listActors} from './graphql/queries'
Also, make sure to configure imported Amplify using the correct configurations.
import awsExports from "./aws-exports"; Amplify.configure(awsExports);
Below is the function that we are going to use for fetch actors.
Now the last thing we need to do is calling this fetchActors() function from UseEffect. Remove previously called getActors() method and replace with fetchActors().
Now if all is working it should show only 2 actors which now come from our GraphQL api.
Next, let’s try to add actors using our react application. For this, we are going to use addActor Mutation which we already imported.
Apart from creating addActor() function we need to have input fields as well. Below is the fully completed code for the Home component.
Now let’s try to add an actor and after it should appear on the table.
Now that it is completed let’s move to our final task, deploying and hosting
Now for the last part let’s add the hosting module for our application by issuing the following command.
amplify add hosting
Again we will be prompted with several questions. For the plugin select Hosting with Amplify Control and for the type select Manual deployment.
Now only thing remains is to publish this module to Amplify. For that issue following command.
amplify publish
This will generate a cloudFormation stack and will create necessary infrastructure on AWS.
After a while, all infrastructure will be get created and we will have the deployed URL. You can go ahead and check the URL to make sure every thing works as it should be.
Additionally, rather than making a manual deployment, we have the option of continuous deployment as well from Amplify.
Ok, that’s was a simple guideline for how to deploy a react application using a serverless GraphQL api and using Cognito authentication. Please follow official documentation if you want to know more about AWS Amplify and it’s many more features. Thank you :)