This is an updated rewrite of my 2021 article on protected routes. A lot has changed in the React ecosystem since then. React Router moved from v5 to v7, class components have faded out, and the patterns we use for authentication state have matured. This version reflects how protected routes are built in modern React applications.

Almost every web application requires some form of authentication to prevent unauthorized users from accessing parts of the application meant for signed-in users only.

In this tutorial, I'll show how to set up an authentication flow and protect routes from unauthorized access using modern React patterns: function components, hooks, React Router v6+, and the Context API.

First things first

Install the dependency: