From Zero to Serverless React App with AWS Amplify in Under an Hour
Introduction
AWS Amplify simplifies building and deploying cloud-powered mobile and web applications. This guide walks you through creating a basic React app and deploying it as a serverless application using Amplify – all in under an hour!
Prerequisites
- An AWS account
- Node.js and npm installed
- Basic React knowledge
Step 1: Create a React App
First, create a new React application using Create React App:
npx create-react-app my-amplify-app
cd my-amplify-app
Step 2: Initialize Amplify
Install the Amplify CLI:
npm install -g @aws-amplify/cli
Configure Amplify by running:
amplify configure
This will guide you through setting up an AWS profile with appropriate permissions.
Initialize Amplify in your project:
amplify init
Follow the prompts to configure your project. Choose your preferred editor, JavaScript, React, and accept the default values for most options.
Step 3: Add Authentication
Add authentication to your app:
amplify add auth
Choose the default configuration with email sign-in.
Push the changes to AWS:
amplify push
This will create the necessary AWS resources (Cognito user pool) for authentication.
Step 4: Integrate Authentication in your React App
Install the Amplify libraries:
npm install aws-amplify @aws-amplify/ui-react
Configure Amplify in src/index.js
:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Amplify } from 'aws-amplify';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Create or modify src/App.js
to include authentication components:
import React, { useState, useEffect } from 'react';
import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
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);
Step 5: Deploy the Application
Deploy your application using:
amplify publish
Amplify will build your application and deploy it to an AWS S3 bucket with CloudFront CDN for distribution.
Conclusion
You have successfully created and deployed a serverless React application with authentication using AWS Amplify in a short amount of time. Amplify offers many more features such as GraphQL APIs, storage, and functions. Explore them to build even more powerful applications!