Software systems to innovate and grow

What You Need To Know About Authentication With React

By Engineering Team March 19, 2019 10 mins read

Authentication is a feature that makes your web app more practical and functional. New features allow you to give users access to specific pages, and therefore tailors your application to the needs of each user, adding a lot more possibilities. Having private information linked with your accounts makes it even more important that your users are only able to visit the pages you want to allow them to have access to. We know React provides a great way to design highly functional and dynamic user interfaces, but what can you do to make sure your pages are secure and protected?

Backend API for Authentication

Before we begin protecting your routes, let’s discuss the importance of authenticating users. Let’s take a brief look at what a typical back-end auth system could look like.

Top-Down View of Back-End Authentication

Let’s consider a NodeJS server running Express. Typically I would use PassportJS, which is a fantastic authentication middleware for Express. It’s as flexible and modular as they claim, having over 500 usable strategies that can authenticate users in your apps.

Once you have selected your authentication strategy of choice, verify the existence and credentials of the user that you’re trying to authenticate in your database, generate a JSON Web Token for that session and pass it to the client. This is where it’s stored in the browser’s local storage to be retrieved at any time during the session.

If none of that made sense to you, that’s OK. All you need to know is that as a front-end React developer, you’ll be getting a token and storing it in your browser’s local storage and whenever you need to make a call to a private API, you have to send the token with the request to prove the user’s identity.

Since this is a post about authentication in React, after all, we’ll assume a fake authentication service, for now, to demonstrate private and public routing.

Private Routes with React Router

React Router is the most widely used navigation library for React. This makes it painless to navigate between routes on a SPA built in React. According to their website,

“React Router is a collection of navigational components that compose declaratively with your application”

Note: React Router Web is listed as react-router-dom on NPM to distinguish it from react-router-core and react-router-native which is the React Native version.

Routing with React Router

If you’re not familiar with React Router, all we’re saying is that you define your routes through the Route component, and pass in the component you want to associate with the route.

To make use of React Router, you have to wrap all the elements inside a BrowserRouter tag. This is how you list different routes that you can switch between,

Note: Passing exact means the path must exactly match the location.pathname props

Creating Our Own Private Route

Note, React Router does not come with a built-in private/public route system. You have to build it on top of a typical Route component as a higher order component and add in some additional functionality to make it work as you expect.

This can be broken into three simple steps:

  1. Create a higher-order component for Route
  2. Get the user’s auth status
  3. Render component or redirect based on status

1. Create a Higher-Order Component for Route

Firstly, you have to create a function that wraps a normal component.

Here, you de-structure the props and pull the component you passed to the function. Then you can spread the rest of the props on to the route component from within.

Next, render the component you just passed,

Right now, this component will work exactly like a regular route component. That’s because all the props that pass to this function will also be passed down to the actual route component. This is essentially a higher order component that you’ll use to switch to any routes that the user must be logged in to view.

So what differentiates this component and makes it useful for this scenario?

Notice how you’re using the render inside the route instead of passing the component directly. This is so you can add some logic to your routing. That logic is based on whether the user is authenticated or not.

2. Get the User’s Auth Status

Generally, whether the user is authenticated or not should be stored inside a state container, such as Redux. This way, whenever you need to make decisions based on the status of auth, you can directly inject the required state into that component.

However, for the purpose of this post we assume the user status is coming from a fictional auth service called myAuth.

3. Render Component or Redirect Based on Status

Here, you get your auth boolean value. If the user is authenticated, use the conditional ternary operator here to render the component that you passed initially. Otherwise you will need to use (which is another component from react-router-dom that allows you to navigate to a new location) and redirect the user to a login or home page.

Using Our Private Route

Now, all you need to do to make a route private is to use the PrivateRoute component that was just created. All the props are supplied to the actual Route component, and the route will only render if the auth value is true,

This time, if you try to go to “/”the profile directly, it will redirect you to the home page. Logging in makes it possible to visit the private route.

Note: Right now, if you refresh the browser, you will be logged out automatically. To prevent this, you need to store your JSON Web Token in the browser’s local storage that can be used to authenticate the user the next time they visit the page.

Customizing Your Private Route

The beauty of making your own private route component is that you can play around with it to design the exact UX you want to deliver.

For example, to know where to take the user after login, you can pass the current path as a prop to the redirect in your login component, and redirect to that path after the user is authenticated.

It’s a No-Brainer

Creating your own private routes with React makes it a no-brainer to keep your pages intrusion-free. This, in combination with a lot of other moving parts in your React apps, makes it possible to provide a highly customized user experience to your users. Moreover, libraries such as React Routers continue to make developing in React a more pleasurable experience overall.