Samaila Bala I'm a frontend engineer and technical writer.

AWS Amplify and React Native: A tutorial with examples

6 min read 1781

AWS Amplify and React Native: A tutorial

Editor’s note: This post was updated 3 December 2021 to improve the tutorial and include a new section comparing AWS Amplify and Firebase as authentication solutions.

Authentication helps control user access to critical parts of an application. As such, it is a critical part of virtually all types of software.

In this tutorial, we’ll show you how to set up authentication in a mobile application using React Native and AWS Amplify.

We’ll cover the following in detail:

  • What is AWS Amplify?
  • AWS Amplify vs. Firebase
  • Setting up AWS Amplify
  • Setting up a React Native app
  • Adding AWS Amplify to a React Native application
  • Adding authentication with Amazon Cognito
  • Adding logout functionality

To follow along with this tutorial, you should have:

  • Node ≥ v10.0.0
  • npm ≥ v5.2.0
  • An AWS account
  • Knowledge of JavaScript and React
  • Knowledge of React Native
  • An Android and/or iOS emulator

Let’s get started!

What is AWS Amplify?

AWS Amplify is a set of products and tools by Amazon that helps mobile and frontend web developers build and deploy full-stack applications on Amazon Web Services.

Notable features of AWS Amplify include:

  • Authentication — sign in, sign up, sign out, social authentication, etc.
  • Data store that enables you to persist data online and offline
  • API (GraphQL and REST) that enables you to access your backend data seamlessly
  • Storage solutions that help you manage user content in private, public, or protected
  • Analytics
  • Push notifications that let you send targeted communications to users

AWS Amplify vs. Firebase

If you have worked with Amplify before, you probably also already heard of Firebase. Firebase is Google’s counterpart to AWS Amplify and it also offers cloud services.

So the question that arises is, which service you should use? As during many times in life, the answer is: It depends. Generally speaking, both services offer many similar functionalities like authentication, real-time services, data storing, and so on.

We made a custom demo for .
No really. Click here to check it out.

If you are more of a beginner in the world of cloud services and you’re working on a smaller project, then Firebase can be a better choice. You can get started with your React Native project easier and faster because it doesn’t have as high a learning curve in comparison to AWS Amplify. Also, smaller projects can be developed completely for free with Firebase.

If you’re more experienced or working on a large project, AWS Amplify could be the better solution for developing a full-stack React Native app — especially if your project will become bigger with time, the pricing model and the awesome scalability of AWS Amplify are definitely huge pros.

Setting up AWS Amplify

In order to use Amplify, you first need to create an AWS Account and have the Amplify CLI installed. Open a terminal and paste the code below to install the Amplify CLI.

Please note, that the following settings are not project-specific settings. That’s why we install the Amplify CLI globally on our machine.

npm install -g @aws-amplify/cli 

After a successful installation of the Amplify CLI, run the following code to configure the CLI.

amplify configure

This interactive CLI command requires your input at two steps before it completes successfully. These steps are:

  • Authenticating your AWS account
  • Adding an identity and access management (IAM) user

When creating a user, be sure to create a user with AdministratorAccess to AWS services such as Amplify, Cognito, and Cloudfront. This is necessary for:

  • Specifying an AWS region
  • Adding the accessKeyId and the secretAccessKey of the user created
  • Adding an AWS profile

The screenshot below shows a summary of the aforementioned steps:

A summary of the configuration steps

Setting up a React Native app

We use Expo to bootstrap our React Native application. Expo is a framework that helps you develop, build, and, deploy projects that run natively on all your users’ devices.

To get started with Expo, launch a terminal and paste the following code:

npm install --g expo-cli

The command above installs the Expo CLI. After installation, we can initialize a React Native project with the Expo CLI. Paste and run the code below:

expo init aws-amplify-authentication-tutorial

When prompted to choose a template, choose a blank template:

Choose a blank template

After successful installation, a React Native project called aws-amplify-authentication-tutorial appears in the directory where the command was executed. To change into the newly created directory, use the following command:

cd aws-amplify-authentication-tutorial

Adding AWS Amplify to a React Native application

Now that we have a React Native application and the Amplify framework set up, we need to connect Amplify to our React Native application.

Navigate to the React Native application directory and run this command:

amplify init

Running the Amplify init command

You’ll be prompted to specify the following:

  • Name of the project
  • Name of the environment — I’d recommend sticking with the default dev since we are in a development environment (to choose the default option, press enter)
  • Your default editor of choice
  • The type of app you’re building (JavaScript)
  • The JavaScript framework you’re using (React Native)
  • Source directory path (press enter to choose the default root directory)
  • Distribution directory path (press enter to choose the default root directory)
  • Build command (press enter to choose the default command)
  • Start command (press enter to choose the default command)
  • Whether you want to use an AWS Profile (input Yes and press enter)
  • If yes, which profile you want to use

Upon completion of this form:

  • A folder called amplify is created in your applications root directory to store the backend configuration of your application, such as authentication
  • A file called aws-exports.js is created in the source directory path we specified when initializing Amplify. This file contains the information for the services you create with Amplify
  • The .gitignore file is modified to include files and folders generated by Amplify that shouldn’t be added to your Git repository
  • A cloud project is generated in the AWS Amplify Console. You can access it anytime by running amplify console

Next, we have to install some local Amplify dependencies. Paste the following in your terminal:

npm install aws-amplify aws-amplify-react-native @react-native-community/netinfo @react-native-async-storage/async-storage @react-native-picker/picker

Open the App.js file in your code editor and add the following lines of code after the last import statement:

import Amplify from 'aws-amplify';
import config from "./src/aws-exports";
Amplify.configure({
  ...config,
  Analytics: {
    disabled: true,
  },
});

With this setup, we explicitly disabled analytics services in line 6. If you want the default setup, just use Amplify.configure(config) instead of the code in lines 3-8. For the purpose of this tutorial, you can use either method.

We’ve successfully added Amplify to our React Native project. Run expo start to launch the project in your emulator of choice.

Adding Amplify auth to React Native

Amazon Amplify uses Amazon Cognito under the hood to power the authentication process. Amazon Cognito is a service that simplifies the process of adding authentication (sign up, sign in, sign out, OAuth, multifactor authentication, etc.).

To get started, open a terminal in your project root directory and run:

amplify add auth

On the interactive prompt that shows up after entering the command:

  • Choose the default configuration
  • Also choose the way you want users to sign in to the application

Option to choose the default config
After initializing the authentication service, run the command below to deploy it:

amplify push

At this point, we can integrate the authentication service in our application. The Amplify framework provides inbuilt, customizable UI components that are easy to integrate, which helps streamline the process.

Go to your App.js and add the following line below the import statements:

import { withAuthenticator } from 'aws-amplify-react-native';

withAuthenticator is a higher-order component that automatically detects the authentication state of the application and updates the UI.

Change the default export at the end of App.js to the following:

export default withAuthenticator(App)

Your App.js should look similar to this:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Amplify from 'aws-amplify';
import config from "./src/aws-exports";
import { withAuthenticator } from 'aws-amplify-react-native';
Amplify.configure({
  ...config,
  Analytics: {
    disabled: true,
  },
});
function App() {
  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
export default withAuthenticator(App);

Save and run the app in your simulator:

expo start

You should see something like this:

Our new Create New Account screen

Our new Sign In screen

Our new Reset Password screen

Adding logout functionality

After a successful authentication, the user is taken to the app screen and has no way of logging out.

Our successful logout screen

To add a sign out button, create a Home.js file in the root directory and paste the following:

import React from 'react';
import { StyleSheet, Text, View, Pressable, Dimensions } from 'react-native';
import { Auth } from 'aws-amplify';
const { width } = Dimensions.get('window');
const Home = () => {
  const signOut = async () => {
    try {
      await Auth.signOut({ global: true });
    } catch (error) {
      console.log('error signing out: ', error);
    }
  };
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerText}>Welcome!</Text>
        <Pressable style={styles.button} onPress={() => signOut()}>
          <Text style={styles.buttonText}>Sign out</Text>
        </Pressable>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    width: width,
    paddingVertical: 20,
  },
  header: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 20,
    width: width,
    alignItems: 'center',
  },
  headerText: {
    fontSize: 28,
    fontWeight: 'bold',
  },
  button: {
    backgroundColor: '#ff9900',
    padding: 10,
    borderRadius: 6,
  },
  buttonText: {
    color: '#fff',
    fontSize: 18,
  },
});
export default Home;

This creates a Home component that renders a welcome message and a sign out button. When the user clicks the sign out button, it calls the Auth.signOut() method, which is one of the many methods provided by the Auth class of aws-amplify. This method signs the user out.

Open your App.js file and refactor it to include the Home component:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, View } from 'react-native';
import Amplify from 'aws-amplify';
import config from "./src/aws-exports";
import { withAuthenticator } from 'aws-amplify-react-native';
import Home from './Home';
Amplify.configure({
  ...config,
  Analytics: {
    disabled: true,
  },
});
function App() {
  return (
    <View style={styles.container}>
      <Home />
      <StatusBar style="auto" />
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
export default withAuthenticator(App);

Your screen should look like this after saving:

Successfully added a sign out button at the top right of the screen

You can now sign out of the application.

Conclusion

In this tutorial, we walked through how to use the AWS Amplify Framework to authenticate users in a React Native application. The Amplify Framework offers many more features that we didn’t get a chance to cover.

The repository of this application built in this tutorial is available on GitHub. If you have any questions, feel free to drop them in the comments.

LogRocket: Instantly recreate issues in your React Native apps.

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your React Native apps — .

Samaila Bala I'm a frontend engineer and technical writer.

Leave a Reply