AWS Cognito with React.

Authentication With Cognito and React.js

Rehmat Sayany
2 min readFeb 27, 2020

--

AWS Amplify Authentication module provides Authentication APIs and building blocks for developers who want to create user authentication experiences.

The AWS Amplify framework comes with a CLI to deploy your cloud backend to AWS. We will not be using this in our project because we are using Serverless Framework for this purpose.

We will still use the AWS Amplify framework and its React components using the manual setup.

Let’s get started.

Create a React Application

npx create-react-app front-end
cd front-end
npm start

Automate process

amplify add auth

he CLI prompts will help you to customize your auth flow for your app. With the provided options, you can:

  • Customize sign-in/registration flow
  • Customize email and SMS messages for Multi-Factor Authentication
  • Customize attributes for your users, e.g. name, email
  • Enable 3rd party social providers, e.g. Facebook, Twitter, Google and Amazon

After configuring your Authentication options, update your backend:

amplify push

A configuration file called aws-exports.js will be copied to your configured source directory, for example ./src.

Configure Your App

Add Amplify to your app with yarn or npm:

npm add aws-amplify

In your app’s entry point i.e. App.js, import and load the configuration file:

import Amplify, { Auth } from 'aws-amplify';
import awsconfig from './aws-exports';
Amplify.configure(awsconfig);

The default implementation uses the Amplify UI styling, for an example of what that looks like out of the box on web and mobile, see here.

Just add these two lines to your App.js:

import { withAuthenticator } from 'aws-amplify-react'; // or 'aws-amplify-react-native';
import Amplify from 'aws-amplify';
// Get the aws resources configuration parameters
import awsconfig from './aws-exports'; // if you are using Amplify CLI

Amplify.configure(awsconfig);

// ...

export default withAuthenticator(App);

Now, your app has complete flows for user sign-in and registration. Since you have wrapped your App with withAuthenticator, only signed in users can access your app. The routing for login pages and giving access to your App Component will be managed automatically.

Social login can be integrated like google and facebook login but if you would like me to create a tutorial on this let me know in the comments below.

--

--

Rehmat Sayany
Rehmat Sayany

Written by Rehmat Sayany

Full Stack developer @westwing passionate about NodeJS, TypeScript, React JS and AWS.

No responses yet