Step-by-Step Guide: Create a Full Stack Application with AWS Amplify and React

There's been a lot of talk lately about AWS Amplify, but why? , what is it? and what is it for?

AWS Amplify is a set of tools (open source framework, administration user interface, console) and services (static web hosting) that can be used together or individually to be a full stack option for creating a project.

Some of the web and mobile integration options include: Javascript, React, React Native, Angular, Vue, Next.js, Android, iOS, Ionic and Flutter. For some Frameworks, we have what they call UI Components that provide us with useful components for faster development.

However, it can become overwhelming the amount of documentation and options we have.

Today we are going to focus on an application with aws amplify that will consist of creating an application in React, using Amplify to add an authorization with AWS Cognito, creating an API (API GATEWAY) with different paths and connecting it to lambda functions, in this way we have a structure, which according to your need or imagination can serve as a template for infinite projects.

😉 Prerequisites:

  • Node.js v12.x or later
  • npm v5.x or later
  • Git v2.14.1 or later
  • Amplify cli

-- CODE language-powershell -- npm install -g @aws-amplify/cli

amplify configure : para configurar se debe tener una cuenta aws a la que se redirigirá para iniciar sesión.

Once you're logged in, Amplify CLI will ask you to create an IAM user. If you already have a user created, you can return to the terminal, press enter and add your credentials.

(El usuario debe ser AdministratorAccess o con acceso a lo siguiente: AWS Amplify - AppSync - Cognito - API Gateway)
 
Specify the AWS Region
? region:# Your preferred region
Specify the username of the new IAM user:
? user name:# User name for Amplify IAM user
Complete the user creation using the AWS console

Enter the access key of the newly created user:
? accessKeyId:# YOUR_ACCESS_KEY_ID
? secretAccessKey:# YOUR_SECRET_ACCESS_KEY
This would update/create the AWS Profile in your local machine
? Profile Name:# (default)

Successfully set up the new user.

Example:

 
Specify the AWS Region
? region:  us-east-1
? user name:  jazmin@kranio.io
? accessKeyId:  AKIAIOSFODNN7EXAMPLE
? secretAccessKey:  wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
This would update/create the AWS Profile in your local machine
? Profile Name:  kranio

Successfully set up the new user.

🚀 Now it's time to start with the project:

We are going to go step by step, some steps have one or more ways to implement, you can follow the option that best suits you.

🧠 Step 1: Create React App

 
npx create-react-app "nombre de carpeta nueva o una ya conectada a un repositorio(bitbucket-gitHub-gitLab)"

example:

npx create-react-app AmplifyReactProject
cd AmplifyReactProject

🧠 Step 2: Start Amplify

  • Fact: Amplify has a series of very complete commands that will help us to do everything we need from our terminal.
comandos aws amplify

In the following code block you can see an example of how to start Amplify in your React App:

 
Enter a name for the project (AmplifyReactProject)

# All AWS services you provision for your app are grouped into an "environment"
# A common naming convention is dev, staging, and production
Enter a name for the environment (dev)

# Sometimes the CLI will prompt you to edit a file, it will use this editor to open those files.
Choose your default editor # example: VS Code

# Amplify supports JavaScript (Web & React Native), iOS, and Android apps
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 build)

Start command (npm start)

# This is the profile you created with the `amplify configure` command in the introduction step.
Do you want to use an AWS profile

MORE INFO: https://docs.amplify.aws/start/getting-started/setup/q/integration/react/#initialize-a-new-backend

🧠 Step 3: Install amplify libraries (React)

 

npm install aws-amplify @aws-amplify/ui-react


🧠 Step 4: Configure Frontend

Abra src / index.js y agregue el siguiente código debajo de la última importación:
 
import Amplify from "aws-amplify";
import awsExports from "./aws-exports";
Amplify.configure(awsExports);

The file aws-exports is a configuration file generated by ampify.

🧠 Step 5: Create or import Auth (Cognito) to Amplify

If you don't have an existing Cognito you can create one like this:

 
$amplify add auth

? Do you want to use the default authentication and security configuration? Default configuration
? How do you want users to be able to sign in? Username
? Do you want to configure advanced settings?  No, I am done.

$amplify push

Import an existing Cognito:

 

amplify import auth


MORE INFO: https://docs.amplify.aws/cli/auth/import/

🧠 Step 6: Use auth to login on the front-end

To use this authorization (created or imported) in our App, we have two ways:

  • With WithAuthenticator:
Abra   src / App.js y realice los siguientes cambios:
🔹 Importar los componentes AmplifySignOut : withAuthenticatory y AmplifySignOut :
 

import { withAuthenticator, AmplifySignOut } from "@aws-amplify/ui-react";


🔹 Agregue el componente AmplifySignOut al principio del todo: Este componente nos ayuda a salir de la session.
 


🔹 Cambie la exportación predeterminada para que sea la withAuthenticator envoltura del componente principal:
 

export default withAuthenticator(App)


🔹 Ejecute la App con npm start y debería ver esto:
login screen: enter sername and password and click sign in button

🔹 Now to access your app you must create an account (cognito), for that you can use the option create account, confirm with your email and log in.

🔹 But you also have the option of accessing Cognito from the aws console, searching for your UserPool and adding users manually:

consola de cognito para definir usuarios manulamente
If it is a private application, it is recommended to disable the option. Create account and only create accounts from the console, so anyone will not sign in or be able to create accounts.

🔹 To disable create account. In the section Policies answer the second question with the option: Allow only administrators to create users.

consola para definir niveles de seguridad
  • With Customization:

We have the option of customizing our Login, for that we need knowledge about the library that is being used, in this case React. You can get an idea with this documentation:

https://docs.amplify.aws/lib/auth/emailpassword/q/platform/js/#custom-attributes

https://docs.amplify.aws/start/getting-started/auth/q/integration/react/#create-login-ui

🧠 Step 7: Create an API Gateway with amplify (REST)

When creating an API we have many possibilities, today we will see how to add two paths linked each to a different lambda function.

Before creating the API, let's understand what we want to achieve. We're going to join lambda functions to different paths in our API.

In this way:

🔹 Para el path /pathOne se creará una función {lambdaExampleOne}
🔹 Para el path /pathTwo se creará una función {lambdaExampleTwo}

When creating our API we will have to create a path immediately, so we are going to add one in this step and then we will see how to add another one.

  • When adding a function, it gives us three options such as “template”, each one has different purposes:
 

? Choose the function template that you want to use: (Use arrow keys)
❯ Hello world function
  CRUD function for Amazon DynamoDB table (Integration with Amazon API Gateway and Amazon DynamoDB)
  Serverless express function (Integration with Amazon API Gateway)


• El Hello World function creará una función básica de Lambda hello world
• La CRUD function for Amazon DynamoDB table (Integration with Amazon API Gateway and Amazon DynamoDB) función agregaría una plantilla de función Lambda predefinida sin servidor-express para operaciones CRUD a las tablas de DynamoDB (que puede crear siguiendo las indicaciones de la CLI o usar las tablas que ya ha configurado con el amplify add storagecomando)
• La Serverless express function (Integration with Amazon API Gateway) añadirá un predefinido expresar sin servidor- Lambda plantilla de función con el enrutamiento habilitado para sus rutas de API REST

MORE INFO: https://docs.amplify.aws/cli/function/#set-up-a-function

 

$amplify add api

? Please select from one of the below mentioned services:
    `REST`
? Provide a friendly name for your resource to be used as a label for this category in the project:
    `KranioApiExample`
? Provide a path (e.g., /book/{isbn}):
    `/pathOne`
? Choose a Lambda source
    `Create a new Lambda function`
? Provide a friendly name for your resource to be used as a label for this category in the project:
    `kranio`
? Provide the AWS Lambda function name:
    `lambdaExampleOne`
? Choose the function runtime that you want to use:
    `NodeJS`
? Choose the function template that you want to use:
    `Serverless ExpressJS function (Integration with API Gateway)`
? Do you want to access other resources created in this project from your Lambda function?
    `No`
? Do you want to invoke this function on a recurring schedule?
    `No`
? Do you want to edit the local lambda function now? `No`
Successfully added the Lambda function locally
? Restrict API access
    `Yes`
? Who should have access?
    `Authenticated`
? What kind of access do you want for Authenticated users?
    `create, read, update, delete`
Successfully added auth resource locally.
? Do you want to add another path?
    `No`
$amplify push


Once the API is created, we can import it and configure it in our App.

Por ejemplo en App.js en React o main.ts en Angular:
 


We also have the option of importing an existing API just by omitting the creation and adding it to the configuration directly.

This configuration allows us to make direct requests to the API, for example for a GET:

 

import { API } from "aws-amplify";

const apiName = 'MyApiName';
const path = '/path';
const myInit = { // OPTIONAL
    headers: {}, // OPTIONAL
    response: true, // OPTIONAL (return the entire Axios response object instead of only response.data)
    queryStringParameters: {  // OPTIONAL
        name: 'param',
    },
};

API
  .get(apiName, path, myInit)
  .then(response => {
		console.log(response);
    // Add your code here
  })
  .catch(error => {
    console.log(error.response);
 });


🧠 Step 8: Add another path to our API

In the previous step we created our API and configured it, now we are going to add a new path and we are going to join it to a new Lambda function just like the previous path.

 

// Opciones para agregar, actualizar o eliminar path:

$ amplify api update
? Please select from one of the below mentioned services: REST
? Please select the REST API you would want to update KranioApiExample
? What would you like to do
> Add another path
  Update path
  Remove path


 

$ amplify api update
? Please select from one of the below mentioned services: REST
? Please select the REST API you would want to update KranioApiExample
? What would you like to do Add another path
? Provide a path (e.g., /book/{isbn}): /pathTwo
? Choose a Lambda source (Use arrow keys)
> Create a new Lambda function
  Use a Lambda function already added in the current Amplify project


These actions generated folders with the resources inside the Amplify/BackEnd directory, where we can work on the functionality for the lambdas.

estructura de carpetas y recursos

🧠 Step 9: Amplify Deploy

After creating our resources in amplify, both the frontend and the backend, we need to implement them. For this we have several possibilities.

We have the command:

 

amplify push

To implement only the backend of our amplify project.

We also have the command:

 

amplify publish


Which will apply both the frontend and the backend of our project. But to implement the frontend, first we have to create a hosting which consists of a structure that will house the web application, we have three: amplify console, directly in an S3 bucket or a combination of an S3 bucket with Cloudfront.

For this we use the command:

 

amplify add hosting

MORE INFO: https://docs.amplify.aws/cli/hosting/hosting/

Amplify CI/CD

We have two possibilities to have a continuous deployment pipeline with amplify: manual or automated by amplify. When doing an add hosting you can choose how you want to do it, the interesting thing is that you can have a specific type for each environment and a format in dev, a format in a feature branch, a format for qa, always choosing what best suits you.

The following is an example of an automated Amplify deployment:

  • We first located the front environment of our App in AWS Amplify and connected it to our repository:
selecion de template para frontend
  • Then we choose the branch where we want to deploy, in this case Develop, however, as mentioned above, you can configure as many automated deployments as there are branches in our project.
seleccionar rama y configuración
  • The next thing is to select our application in the environment (dev) and add a role with access to amplify. If there is none you can easily create in the Create new role option and follow the steps indicated, then refreshing so that it appears is enough.
seleccionar aplicación en el enviroment(dev)
  • This is necessary to continue:
llenar campos obligatorios
  • Before proceeding to the next step, click on the box: Allow AWS Amplify to automatically deploy all files hosted in your project root directory
click para permitir deploy automatico aws amplify
  • Finally We Push Save and Deploy And that's all, the application will start deploying:
iniciar el desplieuge (deploy) de la aplicación
confirmación del deploy de la aplicación con aws amplify

🧠 Conclusion

Finally, now you know what amplify is, its options, and you have an example guide on how to implement Backend services such as API Gateway, Cognito, Lambda Functions with a specific Front-End library. You have a process for creating an application with aws amplify. It's time to adapt it to your needs. Whether you have a front application that needs a fast and scalable backend or if you want to start from scratch, this will undoubtedly be a good option.

Do you have an idea? Don't you know how to start? Write to us.

Co-author: Gustavo Matozinho

Team Kranio

September 16, 2024