Building a Serverless React App with AWS Amplify
Introduction
AWS Amplify is a powerful framework and platform that simplifies building and deploying cloud-powered mobile and web applications. In this tutorial, we'll walk through creating a simple React application and deploying it serverlessly using Amplify.
Prerequisites
- An AWS account
- Node.js and npm installed
- Amplify CLI installed and configured:
npm install -g @aws-amplify/cli
andamplify configure
Creating the React App
Let's start by creating a new React application using Create React App:
npx create-react-app amplify-react-app
cd amplify-react-app
Initializing Amplify
Now, initialize Amplify within your project:
amplify init
Follow the prompts in the CLI to configure your project. Choose sensible defaults for your project name, environment, and editor. When prompted to choose an authentication method, select "AWS profile" if you have configured your AWS CLI.
Adding Authentication
Let's add authentication to our app using Amazon Cognito:
amplify add auth
Choose the default configuration for easy setup. After configuring, push the changes to AWS:
amplify push
This will provision the necessary resources in your AWS account.
Integrating Authentication into React
Install the Amplify libraries:
npm install aws-amplify @aws-amplify/ui-react
Import the necessary modules in your src/App.js
file:
import React, { useState, useEffect } from 'react';
import { Amplify } from 'aws-amplify';
import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
function App({ signOut, user }) {
return (
<div className="App">
<Heading level={1}>Hello {user.username}</Heading>
<Button onClick={signOut}>Sign out</Button>
</div>
);
}
export default withAuthenticator(App);
Configure Amplify with your project's AWS exports. These are in src/aws-exports.js
. The withAuthenticator
higher-order component handles authentication flow, displaying a sign-up/sign-in form if the user isn't authenticated.
Deploying the Application
Deploy your application to AWS Amplify Hosting:
amplify add hosting
Choose the "Hosting with Amplify Console" option, then select the defaults for the remaining prompts. Finally, deploy:
amplify push
amplify publish
Amplify will build and deploy your application to a unique URL. You'll see the URL in the console output.
Conclusion
In this tutorial, we learned how to build a simple React application and deploy it serverlessly using AWS Amplify. Amplify significantly simplifies the development and deployment process, allowing you to focus on building your application's features. You can expand this further by adding APIs, databases and more, all managed by Amplify.