success_logo

Your form has successfully submitted

One of our teammates will get back to you soon.

Getting started with serverless using Amplify + React - Part 1: Scaffolding

This tutorial aims to give an introduction to creating serverless web applications in the cloud. There are several providers of serverless tools, we will work with AWS Amplify which allows grouping and managing the tools that the application will use from a single console and with a single CLI. We will create a React application that allows authentication through Cognito, create endpoints to Lambda functions, save data in Dynamo DB, and additionally we will configure a CI/CD pipeline.


What is Amplify?

Amplify is an AWS tool designed specifically for front-end development. It removes the burden of having to configure all the hosting services, database, and even authentication which is arguably one of its best attributes.

It is one of the best ways to get started in the serverless world, as it is quick and relatively easy to install, configure and use. The ability to reuse the same backend and configured services for various use cases such as a mobile application, website, e-commerce, or any front end that needs these services is a huge advantage for the product.

Another very important feature is the possibility to scale up and down by including new services according to what is needed. Even the administration is quite versatile, you can manage several environments (dev, staging, production) and the whole team can have access through IAM users and the Amplify CLI.

About the tutorial:

This tutorial will cover the setup of a React application using Amplify with the following features:

  • Cognito for authentication
  • GraphQL API
  • Creating the API mutations in React
  • Add hosting
  • Configure a CI/CD pipeline

We will build a real-world application with all the basic backend and frontend features the application needs.

What is the project about?

It will be an application for a customizable t-shirt business. It will allow customers to customize the t-shirt with their favorite print and place their order at the store.

Once the customer places the order, confirmation emails will be sent to the customer and the store owner.

The owner will be able to review the order and update the order status, letting the customer know where the order is in the process.

Index:

This tutorial is split into four parts. If you are looking for a specific part of this tutorial, here is the index:

  1. Scaffolding
  2. Prerequisites
  3. Setting up AWS Amplify CLI
  4. Scaffold the React application
  5. Initialize the Amplify project and add authentication
  6. Add the API
  7. Add the GraphQL API
  8. Use the API in the React frontend
  9. Control access to the API according to user permissions
  10. Deploy the application
  11. Deploy and host the application with CI/CD
  12. Conclusions

Prerequisites

  • It will make it easier to follow this tutorial if you are familiar with JS, React, basic CLI commands, and Git
  • You will need to install:
  • node v14.18 or later
  • npm v6.14.4 or later
  • git v2.14.1 or later
  • Even though knowledge of AWS is not required I would recommend having a basic understanding of what serverless is.

Setting up AWS Amplify CLI

The first step is to set up the Amplify CLI and hook it up with your AWS account. To install the CLI as easy as it gets, just run:

npm install -g @aws-amplify/CLI

Setting up the AWS account may take a little longer:

  1. Create an AWS account in aws.amazon.com and log in to the console. If it is your first time you will have access to the free tier.
  2. Configure the Amplify CLI running:
  3. amplify configure
  4. This command will ask you to log in and create a profile. You can check this aws video tutorial or follow these steps to complete the configuration:
  5. Log in to the console
  6. Specify the region. You can see that in the upper right corner of the console.
  7. Create the IAM user (This user creates authorization credentials with the permissions you choose)
    1. Insert the user name
    2. Choose the permissions set. Should be only AdministratorsAccess-Amplify
    3. Add tags if you want
    4. Review
    5. Copy the credentials and insert this into your CLI

This is the summary of what would happen in your console:

And that was it, now you have complete access to Amplify and its services from the CLI.

Scaffold the React application

Usually for a tutorial, “create react app” is used to bootstrap the react application. As this is a more real-world application these are a set of tools to be used:

  • Vite: Bundler
  • Typescript: Programming language
  • Jest: Testing framework
  • AWS UI: UIKit and Cloudscape Design System
  • Prettier: Code formatter
  • Linter: Eslint
  • Yarn: Package manager

To install all the packages run the following commands:

Initialize your npm project and follow the instructions:

npm init

Install dependencies

yarn add @aws-amplify/ui-react @awsui/collection-hooks @awsui/components-react @awsui/global-styles @reach/router aws-amplify jest react react-dom react-error-boundary

Install dev dependencies

yarn add @types/react @types/react-dom @vitejs/plugin-react eslint eslint-config-prettier eslint-plugin-prettier prettier typescript vite ts-jest --dev

Create the TS configuration file at the root of the project:

tsconfig.json

Here are some of the configurations to use:

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "outDir": "./dist/",
    "baseUrl": "./",
    "jsx": "react",
    "target": "ESNext",
    "useDefineForClassFields": true,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "module": "ESNext",
    "noEmit": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "sourceMap": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": false,
    "alwaysStrict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
  },
  "include": ["src", "test"]
}

Bundler configuration:

vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: [
      {
        find: "./runtimeConfig",
        replacement: "./runtimeConfig.browser",
      },
    ],
  },
});

Also, vite requires an index.html as an entry for the react project. This can be the content of that file:

Index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Amplify T-Shirt tutorial</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/index.tsx"></script>
    <script>
      window.global = window;
      window.process = {
        env: { DEBUG: undefined },
      };
      var exports = {};
    </script>
  </body>
</html>

Jest configuration:

Jest.config.js

module.exports = {
  preset: "ts-jest",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/test/setUpTest.ts"],
};

Don't forget about git, init your project and add a gitignore file.

git init

.gitignore

Here you can use a .gitignore generator like https://www.toptal.com/developers/gitignore and generate a file for React and node that should be enough for the moment.

Add the prettier configuration, here are some of the settings used for this project:

{
 "trailingComma": "es5",
 "tabWidth": 2,
 "semi": true,
 "singleQuote": true,
 "endOfLine": "lf"
}

Also, add a .prettierignore to avoid touching the auto-generated files from Amplify:

node_modules
.gitignore
.prettierignore
.prettierrc.json
.graphqlconfig.yml
package.json
tsconfig.json
vite.config.ts
yarn.lock
jest.config.js
.vscode
.eslintignore
yarn-error.log
.husky
amplify.yml

# Ignore all HTML files:
*.html

# Ignore amplify autogenerated files
**/.js
src/API.ts
amplify
build
dist
src/aws-exports.js
src/graphql

Create scripts to test, start and build the application. These scripts should be located in the package.json as follows:

"scripts": {
  "test": "jest",
  "start": "vite",
  "build": "tsc && vite build"
}

And finally, create the entry point of the application which should be located in the src folder. Usually, you can place it in the root but for better functionality of Amplify locating the app and entry point in the src folder is better.

And to start, its contents should be:

index.tsx

import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(<h1>MyApp</h1>, document.getElementById("root"));

So, finally, the files should end up looking like this:

And when you run yarn start the dev server should start in http://localhost:3000/ showing “MyApp” in the browser.

Demo source code:

Check the full source code of this part of the tutorial here: https://github.com/stackbuilders/blog-code/tree/main/amplify-react-tutorial/part-1-scaffold-react-app

Next Steps:

With these steps, we got nothing but a normal React application and some dependencies installed. To integrate amplify it’s necessary to initialize the amplify project, for that be sure to have the amplify CLI installed as described in the first step and go to Part 2 of this tutorial.

Published on: Nov. 2, 2022

Written by:


NatalyRocha

Nataly Rocha