Javascript is required
·
10 min read
·
3875 views

Build and Deploy a Serverless GraphQL React App Using AWS Amplify

Build and Deploy a Serverless GraphQL React App Using AWS Amplify Image

Recently I recognized that some SaaS (Software as a Service) products use AWS Amplify which helps them to build serverless full-stack applications. I think serverless computing will be the future of apps and software. Therefore, I wanted to gather some hands-on experience, and I built a serverless application using AWS Amplify that uses React as frontend framework and GraphQL as backend API.

In this article, I want to guide you through the process how to build and deploy such an Amplify application.

Set up Amplify

AWS Amplify describes itself as:

Fastest, easiest way to build mobile and web apps that scale

Amplify provides tools and services to build scalable full-stack applications powered by AWS (Amazon Web Services). With Amplify configuring backends and deploying static web apps is easy. It supports web frameworks like Angular, React, Vue, JavaScript, Next.js, and mobile platforms including iOS, Android, React Native, Ionic, and Flutter.

You'll need to create an AWS account to follow the following steps. No worries, after signing up you have access to the AWS Free Tier which does not include any upfront charges or term commitments.

The next step is to install the Amplify Command Line Interface (CLI). In my case I used cURL on macOS:

bash
curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL

Alternatively, you can watch this video to learn how to install and configure the Amplify CLI.

Now we can configure Amplify using the CLI

bash
amplify configure

which will ask us to sign in to AWS Console. Once we’re signed in, Amplify CLI will ask us to create an AWS IAM user:

bash
1Specify the AWS Region
2? region:  # Your preferred region
3Specify the username of the new IAM user:
4? user name:  # User name for Amplify IAM user
5Complete the user creation using the AWS console

We'll be redirected to IAM where we need to finish the wizard and create a user with AdministratorAccess in our account to provision AWS resources. Once the user is created, Amplify CLI will ask us to provide the accessKeyId and secretAccessKey to connect Amplify CLI with our created IAM user:

bash
1Enter the access key of the newly created user:
2? accessKeyId:  # YOUR_ACCESS_KEY_ID
3? secretAccessKey:  # YOUR_SECRET_ACCESS_KEY
4This would update/create the AWS Profile in your local machine
5? Profile Name:  # (default)
6
7Successfully set up the new user.

Set up full-stack Amplify project

At this point, we are ready to set up our full-stack project using a React application in the frontend and GraphQL as backend API. We'll build a Todo CRUD (create, read, update, delete) application that uses this architecture:

Amplify demo architecture

The complete source code of this demo is available at GitHub.

Create React frontend

Let's start by creating a new React app using create-react-app. From our projects directory we run the following commands to create our new React app in a directory called amplify-react-graphql-demo and to navigate into that new directory:

bash
1npx create-react-app amplify-react-graphql-demo
2cd amplify-react-graphql-demo

To start our React app we can run

bash
npm start

which will start the development server at http://localhost:3000.

Initialize Amplify

Now it's time to initialize Amplify in our project. From the root of the project we run

bash
amplify init

which will prompt some information about the app:

bash
1 amplify init
2? Enter a name for the project amplifyreactdemo
3The following configuration will be applied:
4
5Project information
6| Name: amplifyreactdemo
7| Environment: dev
8| Default editor: Visual Studio Code
9| App type: javascript
10| Javascript framework: react
11| Source Directory Path: src
12| Distribution Directory Path: build
13| Build Command: npm run-script build
14| Start Command: npm run-script start
15
16? Initialize the project with the above configuration? Yes
17Using default provider  awscloudformation
18? Select the authentication method you want to use: AWS profile
19? Please choose the profile you want to use: default

When our new Amplify project is initialized, the CLI:

  • created a file called aws-exports.js in the src directory that holds all the configuration for the services we create with Amplify
  • created a top-level directory called amplify that contains our backend definition
  • modified the .gitignore file and adds some generated files to the ignore list

Additionally, a new cloud project is created in the AWS Amplify Console that can be accessed by running amplify console. Amplify Console provides two main services: hosting and the Admin UI. More information can be found here.

The next step is to install some Amplify libraries:

bash
npm install aws-amplify @aws-amplify/ui-react typescript
  • aws-amplify: the main library for working with Amplify in your apps
  • @aws-amplify/ui-react: includes React specific UI components
  • typescript: we will use TypeScript in some parts of this demo

Next, we need to configure Amplify on the client. Therefore, we need to add the following code below the last import in src/index.js :

1import Amplify from 'aws-amplify'
2import awsExports from './aws-exports'
3Amplify.configure(awsExports)

At this point wee have a running React frontend application, Amplify is configured, and we can now add our GraphQL API.

Create GraphQL API

We will now create a backend that provides a GraphQL API using AWS AppSync (a managed GraphQL service) that uses Amazon DynamoDB (a NoSQL database).

To add a new API we need to run the following command in our project’s root folder:

bash
1 amplify add api
2? Please select from one of the below mentioned services: GraphQL
3? Provide API name: demoapi
4? Choose the default authorization type for the API: API key
5? Enter a description for the API key:
6? After how many days from now the API key should expire (1-365): 7
7? Do you want to configure advanced settings for the GraphQL API: No, I am done.
8? Do you have an annotated GraphQL schema? No
9? Choose a schema template: Single object with fields (e.g., “Todo” with ID, name, description)

After the process finished successfully we can inspect the GraphQL schema at amplify/backend/api/demoapi/schema.graphql:

graphql
1type Todo @model {
2  id: ID!
3  name: String!
4  description: String
5}

The generated Todo type is annotated with a @model directive that is part of the GraphQL transform library of Amplify. The library contains multiple directives which can be used for authentication, to define data models, and more. Adding the @model directive will create a database table for this type (in our example a Todo table), the CRUD (create, read, update, delete) schema, and the corresponding GraphQL resolvers.

Now it's time to deploy our backend:

bash
1 amplify push
2 Successfully pulled backend environment dev from the cloud.
3
4Current Environment: dev
5
6| Category | Resource name | Operation | Provider plugin   |
7| -------- | ------------- | --------- | ----------------- |
8| Api      | demoapi       | Create    | awscloudformation |
9? Are you sure you want to continue? Yes
10? Do you want to generate code for your newly created GraphQL API: Yes
11? Choose the code generation language target: typescript
12? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.ts
13? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Yes
14? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
15? Enter the file name for the generated code: src/API.ts

After it is finished successfully our GraphQL API is deployed and we can interact with it. To see and interact with the GraphQL API in the AppSync console at any time we can run:

bash
amplify console api

AppSync GraphQL API Console

Alternatively, we can run this command

bash
amplify console api

to view the entire app in the Amplify console.

Connect frontend to API

The GraphQL mutations, queries and subscriptions are available at src/graphql. To be able to interact with them we can use the generated src/API.ts file. So we need extend App.js to be able to create, edit and delete Todos via our GraphQL API:

1import React, { useEffect, useState } from 'react'
2import { API, graphqlOperation } from '@aws-amplify/api'
3
4import { listTodos } from './graphql/queries'
5import { createTodo, deleteTodo, updateTodo } from './graphql/mutations'
6import TodoList from './components/TodoList'
7import CreateTodo from './components/CreateTodo'
8
9const initialState = { name: '', description: '' }
10
11function App() {
12  const [formState, setFormState] = useState(initialState)
13  const [todos, setTodos] = useState([])
14  const [apiError, setApiError] = useState()
15  const [isLoading, setIsLoading] = useState(false)
16
17  useEffect(() => {
18    fetchTodos()
19  }, [])
20
21  function setInput(key, value) {
22    setFormState({ ...formState, [key]: value })
23  }
24
25  async function fetchTodos() {
26    setIsLoading(true)
27    try {
28      const todoData = await API.graphql(graphqlOperation(listTodos))
29      const todos = todoData.data.listTodos.items
30      setTodos(todos)
31      setApiError(null)
32    } catch (error) {
33      console.error('Failed fetching todos:', error)
34      setApiError(error)
35    } finally {
36      setIsLoading(false)
37    }
38  }
39
40  async function addTodo() {
41    try {
42      if (!formState.name || !formState.description) {
43        return
44      }
45      const todo = { ...formState }
46      setTodos([...todos, todo])
47      setFormState(initialState)
48      await API.graphql(graphqlOperation(createTodo, { input: todo }))
49      setApiError(null)
50    } catch (error) {
51      console.error('Failed creating todo:', error)
52      setApiError(error)
53    }
54  }
55
56  async function removeTodo(id) {
57    try {
58      await API.graphql(graphqlOperation(deleteTodo, { input: { id } }))
59      setTodos(todos.filter((todo) => todo.id !== id))
60      setApiError(null)
61    } catch (error) {
62      console.error('Failed deleting todo:', error)
63      setApiError(error)
64    }
65  }
66
67  async function onItemUpdate(todo) {
68    try {
69      await API.graphql(
70        graphqlOperation(updateTodo, {
71          input: {
72            name: todo.name,
73            description: todo.description,
74            id: todo.id,
75          },
76        })
77      )
78      setApiError(null)
79    } catch (error) {
80      console.error('Failed updating todo:', error)
81      setApiError(error)
82    }
83  }
84
85  const errorMessage = apiError && (
86    <p style={styles.errorText}>
87      {apiError.errors.map((error) => (
88        <p>{error.message}</p>
89      ))}
90    </p>
91  )
92
93  if (isLoading) {
94    return 'Loading...'
95  }
96
97  return (
98    <div style={styles.container}>
99      <h1 style={styles.heading}>Amplify React & GraphQL Todos</h1>
100      {errorMessage}
101      <div style={styles.grid}>
102        <TodoList todos={todos} onRemoveTodo={removeTodo} onItemUpdate={onItemUpdate} />
103        <CreateTodo
104          description={formState.description}
105          name={formState.name}
106          onCreate={addTodo}
107          onDescriptionChange={setInput}
108          onNameChange={setInput}
109        />
110      </div>
111    </div>
112  )
113}
114
115export default App

The full source code of this demo is available at GitHub.

The application should show a list of available Todos which can be edited or deleted. Additionally, we have the possibility to create new Todos:

Amplify Frontend Running Locally

Add authentication

Amplify uses Amazon Cognito as the main authentication provider. We'll use it to add authentication to our application by adding a login that requires a password and username.

To add authentication we need to run

bash
1 amplify add auth
2Using service: Cognito, provided by: awscloudformation
3 The current configured provider is Amazon Cognito.
4
5 Do you want to use the default authentication and security configuration? Default configuration
6 Warning: you will not be able to edit these selections.
7 How do you want users to be able to sign in? Username
8 Do you want to configure advanced settings? No, I am done.

and deploy our service by running

bash
amplify push

Now we can add the login UI to our frontend. The login flow can easily be handled by using the withAuthenticator wrapper from the @aws-amplify/ui-react package. We just need to adjust our App.js and import withAuthenticator:

import { withAuthenticator } from '@aws-amplify/ui-react'

Now we need to wrap the main component with the withAuthenticator wrapper:

export default withAuthenticator(App)

Running npm start will now start the app with an authentication flow allowing users to sign up and sign in:

Amplify Login

Deploy and host app

Finally, we want to deploy our app which can be either done manually or via automatic continuous deployment. In this demo I want to deploy it manually and host it as static web app. If you want to use continuous deployment instead, please check out this official guide.

First, we need to add hosting:

bash
1 amplify add hosting
2? Select the plugin module to execute: Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
3? Choose a type: Manual deployment

and then we are ready to publish our app:

bash
amplify publish

After publishing, we can see the app URL where our application is hosted on an `amplifyapp.com domain in our terminal.

What's next

Amplify provides also a way to run your API locally, check out this tutorial.

Here are some cool things that you can additionally add to your Amplify application:

Take a look at the official Amplify docs for further information about the framework.

Conclusion

In this article I showed you that building and deploying a full-stack serverless application using AWS Amplify requires a minimum amount of work. Without using such a framework it would be much harder and this way you can focus more on the end product instead of what is happening inside.

If you liked this article, follow me on Twitter to get notified about new blog posts and more content from me.

I will never share any of your personal data. You can unsubscribe at any time.

If you found this article helpful.You will love these ones as well.
How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES Image

How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES

Track Twitter Follower Growth Over Time Using A Serverless Node.js API on AWS Amplify Image

Track Twitter Follower Growth Over Time Using A Serverless Node.js API on AWS Amplify

The 10 Favorite Features of My Developer Portfolio Website Image

The 10 Favorite Features of My Developer Portfolio Website

Create an RSS Feed With Nuxt 3 and Nuxt Content v2 Image

Create an RSS Feed With Nuxt 3 and Nuxt Content v2