DEV Community

Cover image for Protected Routes in React Router V6
Mehrab-18
Mehrab-18

Posted on

Protected Routes in React Router V6

In React router, Private Routes commonly known as 'Protected Routes' are routes that requires a user being authorized to visit that route. Hence if a user is not authorized for a page, they cannot access it.Authorization is far more than only authentication. For example, we can use it when we have roles and permissions in specific areas of the application.

In this article, I want to share with you that how to implement Protected Routes in React Router V6?

Get Source Code

Prerequisites?
Make sure to install react-router and react-router-dom dependencies

File Structure

Image description

We have pages folder where we have all our components and a utils folder where we have a component with our authentication logic.

index.js

Image description

Start from wrapping your component with from react-router-dom

App.js

Image description

So, setting up our App.js we will have component that will contain all of our Routes. Now to protect some routes we will write them inside another component ant this route will be our component that will contain our logic

ProtectedRoutes.js

Image description

This component will have a simple logic i.e. if user's authenticated direct it to the Child component that is our current route path and if a user isn't authenticated navigate it to our home page with path "/". Simple as that!

Hopefully, this article helped you understand implementing protected routes in react router v6. After completely understanding you'll be able to implement Protected Routes in your react app.

Let's Build Safer React Apps!

Top comments (1)

Collapse
 
reacthunter0324 profile image
React Hunter

It's helpful!