How to Set Up Protected Routes in Your React Application

Require authentication for users to access your page

Ferenc Almasi
4 min readFeb 10, 2020
Photo by Ferenc Almasi on Unsplash

Often times, when you’re building a web application, there’s some kind of routing involved with authentication. You want to restrict user access to certain pages or you have your whole application behind a login.

React router is a great way to go by routing, but you don’t really have the option to protect routes from being accessed by anyone. Luckily the solution to this is really simple and straightforward.

In this tutorial, I would like to show you what was my solution to the problem and how I got around it. I’ll start from scratch using create-react-app and only include the absolutely necessary things so you can follow along. Without further ado, let’s jump into coding.

Setting Everything Up

After I bootstrapped the project with create-react-app, I also installed react-router-dom for routing. We won’t need any other dependencies for this project. With not much modification to the initial create-react-app, this is the current state of the package.json file:

--

--

Ferenc Almasi

💻 Frontend dev • ✍️ Creator of webtips.dev • 🐦 Tweets at @WebtipsHQ