AWS Amplify: Building a Serverless Full-Stack React Application

Objective: The objective of this project is to build a full-stack application using AWS services, React, and Amplify. By completing this project, you will gain a deep understanding of how to leverage AWS for serverless backend development, front-end user interface design using React, and the seamless integration of these components using Amplify. You will also learn how to handle user authentication, store and retrieve data from a cloud-based database, and deploy the application to the web.

Learning Outcomes:

  • Understand the fundamentals of serverless architecture and its advantages.
  • Gain proficiency in using AWS services, including AWS Amplify, AWS Cognito, and AWS AppSync.
  • Develop strong skills in React for building interactive user interfaces.
  • Learn how to integrate front-end and back-end components using Amplify.
  • Acquire knowledge in user authentication and authorization.
  • Master the process of data storage and retrieval using a cloud-based database.
  • Gain experience in deploying a full-stack application to the web.

Steps and Tasks:

  1. Set up AWS Account and Install Amplify CLI

    • Create an AWS account at aws.amazon.com.
    • Install the Amplify Command Line Interface (CLI) globally on your machine using npm or yarn.
  2. Initialize a New Amplify Project

    • Open your terminal and navigate to the project directory.
    • Run the command amplify init to initialize a new Amplify project.
    • Follow the prompts to give your project a name, set up an environment, and configure the default text editor.
  3. Set up Authentication with AWS Cognito

    • Run the command amplify add auth to add authentication to your project.
    • Choose the default configuration options for AWS Cognito.
    • Run amplify push to provision the authentication resources in your AWS account.
  4. Create a GraphQL API with AWS AppSync

    • Run the command amplify add api to add a GraphQL API to your project.
    • Choose the default configuration with Amazon DynamoDB as the data source.
    • Define your data model using the GraphQL schema language.
    • Run amplify push to create the API and data resources in your AWS account.
  5. Build the React User Interface

    • Set up a new React application using Create React App or your preferred method.
    • Install the necessary dependencies: npm install aws-amplify @aws-amplify/ui-react graphql.
    • Configure the Amplify library in your React app by creating a new aws-exports.js file and importing it into your app.
    • Create the user interface components for user registration, login, and logout.
  6. Implement User Authentication

    • Import the necessary Amplify components into your authentication pages.
    • Set up state management for user authentication using the Auth category from Amplify.
    • Handle user registration, login, and logout actions using the appropriate Amplify methods.
  7. Add Functionality to the Application

    • Create additional pages or components for your application.
    • Add functionality that requires user authentication, such as a user profile page or restricted content.
  8. Deploy the Application

    • Run the command amplify add hosting to add hosting to your project.
    • Choose the hosting option that best suits your needs (e.g., AWS Amplify Console).
    • Run amplify publish to deploy your application to the web.

Evaluation: The success of this project can be evaluated based on the functionality and deployment of the final application. The application should allow users to register, log in, and access restricted content. The integration between the front-end React application and the AWS services should be seamless, with user authentication handled correctly. The application should also demonstrate the ability to store and retrieve data from the cloud-based database. Successful deployment of the application to the web is also a key evaluation criterion.

Resources and Learning Materials:

Need a little extra help?

  1. Set up AWS Account and Install Amplify CLI

To create an AWS account, simply visit the AWS website (aws.amazon.com) and follow the registration process. Once you have your account set up, you’ll need to install the Amplify CLI. This can be done by running a simple command in your terminal:

npm install -g @aws-amplify/cli
  1. Initialize a New Amplify Project

After installing the Amplify CLI, navigate to your project directory in the terminal and run the following command to initialize a new Amplify project:

amplify init

This command will prompt you to provide a name for your project, set up an environment (e.g., development, production), and configure your default text editor. You can simply follow the on-screen prompts and choose the options that best suit your project.

  1. Set up Authentication with AWS Cognito

To add authentication to your project using AWS Cognito, run the following command:

amplify add auth

This will prompt you to choose from a set of authentication configurations. For most projects, the default configuration provided by AWS is sufficient. You can select it by pressing enter. If you have specific requirements or want to customize your authentication flow, you can explore the other options and refer to the AWS documentation for more information.

  1. Create a GraphQL API with AWS AppSync

To add a GraphQL API to your project using AWS AppSync, run the following command:

amplify add api

This will prompt you to choose from a set of API configurations. Select “GraphQL” and press enter. Next, choose the API service you want to use. AWS AppSync is the recommended option and is selected by default. For data source, you can choose “Amazon DynamoDB” to create a fully managed NoSQL database along with your API. Follow the on-screen prompts to complete the configuration.

As part of the configuration, you will need to define your data model using the GraphQL schema definition language. The schema file is located at amplify/backend/api/{apiName}/schema.graphql. You can open this file and define your data model using the syntax and directives provided by AWS. If you’re new to GraphQL, they also have a lot of examples and documentation to help you get started.

  1. Build the React User Interface

Before you can start building the user interface of your application, you’ll need to set up a React project if you haven’t already. This can be done using Create React App or any other method of your choice. Once your React project is set up, you can install the necessary dependencies by running the following command in your project directory:

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

After installing the dependencies, you’ll need to configure the Amplify library with your AWS credentials. You can do this by creating a new file called aws-exports.js in your project and adding the following code:

const awsmobile = {
  aws_project_region: '<YOUR_AWS_PROJECT_REGION>',
  aws_cognito_region: '<YOUR_AWS_COGNITO_REGION>',
  aws_user_pools_id: '<YOUR_AWS_USER_POOLS_ID>',
  aws_user_pools_web_client_id: '<YOUR_AWS_USER_POOLS_WEB_CLIENT_ID>',
  aws_appsync_graphqlEndpoint: '<YOUR_APPSYNC_API_URL>',
  aws_appsync_region: '<YOUR_APPSYNC_REGION>',
  aws_appsync_authenticationType: 'AMAZON_COGNITO_USER_POOLS',
};

export default awsmobile;

Make sure to replace the placeholder values (<YOUR_XXX>) with the actual values from your AWS account and AppSync API. You can find these values in the AWS console and the aws-exports.js file should be located in the root of your project.

After setting up the configuration, you can start building the user interface of your application by modifying the existing files in your React project or creating new components as needed. You can refer to the React documentation and other resources for best practices and UI design techniques.

  1. Implement User Authentication

To implement user authentication in your React application, you’ll need to import the necessary components from the Amplify library and set up the authentication flow in your application. You can refer to the Amplify Auth documentation for detailed instructions and examples.

Here’s a basic example of how you can set up user authentication with Amplify in your React application:

import React, { useEffect, useState } from 'react';
import { Auth } from 'aws-amplify';

const App = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    checkUser();
  }, []);

  async function checkUser() {
    try {
      const userData = await Auth.currentAuthenticatedUser();
      setUser(userData);
    } catch (err) {
      setUser(null);
    }
  }

  async function signUp() {
    try {
      await Auth.signUp({
        username: 'testuser',
        password: 'Test123!',
      });
      console.log('Sign up successful');
    } catch (err) {
      console.log('Error signing up:', err);
    }
  }

  async function signIn() {
    try {
      await Auth.signIn('testuser', 'Test123!');
      console.log('Sign in successful');
    } catch (err) {
      console.log('Error signing in:', err);
    }
  }

  async function signOut() {
    try {
      await Auth.signOut();
      setUser(null);
      console.log('Sign out successful');
    } catch (err) {
      console.log('Error signing out:', err);
    }
  }

  return (
    <div>
      <h1>My App</h1>
      {user ? (
        <div>
          <p>Welcome, {user.username}!</p>
          <button onClick={signOut}>Sign Out</button>
        </div>
      ) : (
        <div>
          <p>Please sign in:</p>
          <button onClick={signUp}>Sign Up</button>
          <button onClick={signIn}>Sign In</button>
        </div>
      )}
    </div>
  );
};

export default App;

In this example, we use the useEffect hook to check if the user is already signed in when the component mounts. The checkUser function tries to get the current authenticated user using Auth.currentAuthenticatedUser(). If it succeeds, we set the user state. If it throws an error, we set the user state to null.

We define four async functions for user sign up, sign in, and sign out. These functions use the Auth object from Amplify and the user credentials are hard-coded for simplicity. In a real-world application, you would get the username and password from a form input and handle errors more gracefully.

Based on the user state, we render different UI elements. If the user is signed in, we display a welcome message and a sign out button. If the user is not signed in, we display sign up and sign in buttons.

Finally, we export the component and you can continue building your React application as needed.

  1. Add Functionality to the Application

Once you have implemented the basic user authentication, you can start adding more functionality to your application. This could include creating new pages or components, integrating other AWS services, or building out the user profile and settings pages.

You can refer to the documentation and examples for the various categories of the Amplify library (e.g., storage, API, analytics) to explore the different features and capabilities that you can add to your application.

  1. Deploy the Application

To deploy your application, you’ll need to set up hosting for your Amplify project. Run the following command in your project directory:

amplify add hosting

This will prompt you to choose a hosting service. AWS Amplify Console is a great option for hosting and continuous deployment. Follow the on-screen prompts to complete the configuration.

After setting up hosting, you can deploy your application by running the following command:

amplify publish

This will build your React app, configure the necessary backend services in your AWS account, and deploy the application to the web. You will be provided with a unique URL for your deployed application.

And there you have it! You’ve built and deployed a serverless full-stack React application using AWS Amplify. This project serves as a great starting point for exploring more advanced features and services offered by AWS and Amplify. You can experiment with adding data storage, serverless functions, API integrations, and more to further enhance your application.

Remember to refer to the official documentation and resources for detailed information on any specific features or services you want to incorporate into your application. And don’t be afraid to explore and experiment on your own – building projects and learning by doing is the best way to master any technology or framework. Happy coding!

@joy.b has been assigned as the mentor. View code along.