Implement Email/Password Authentication in React
Rate this tutorial
Welcome back to our journey building a full stack web application with MongoDB Atlas App Services, GraphQL, and React!
We will also build the front end of our expense management application, Expengo, using React. By the end of today’s tutorial, we will have the following web application:
Let’s create a brand new React app. Launch your terminal and execute the following command, where “expengo” will be the name of our app:
The process may take up to a minute to complete. After it’s finished, navigate to your new project:
We’ll also install a few other npm packages to make our lives easier:
Finally, let’s create three new directories with a few files in them. To do that, we’ll use the shell. Feel free to use a GUI or your code editor if you prefer.
Open the expengo directory in your code editor. The project directory should have the following structure:
In this section, we will be creating functions and React components in our app to give our users the ability to log in, sign up, and log out.
- Start by copying your App Services App ID:
Now open this file:
Paste the following code and replace the placeholder with your app Id:
Now we will add a new React Context on top of all our routes to get access to our user’s details, such as their profile and access tokens. Whenever we need to call a function on a user’s behalf, we can easily do that by consuming this React Context through child components. The following code also implements functions that will do all the interactions with our Realm Server to perform authentication. Please take a look at the comments for a function-specific description.
This is a wrapper page that will only allow authenticated users to access our app’s private pages. We will see it in action in our ./src/App.js file.
Next, let’s add a login page.
Now our users can log into the application, but how do they sign up? Time to add a signup page!
Our homepage will be a basic page with a title and logout button.
Let’s connect all of our pages in the root React component—App.
All have to do now is run the following command from your project directory:
Woah! We have made a tremendous amount of progress. Authentication is a very crucial part of any app and once that’s done, we can focus on features that will make our users’ lives easier. In the next part of this blog series, we’ll be leveraging App Services GraphQL to perform CRUD operations. I’m excited about that because the basic setup is already over.