• Technologies
  • AI Tips and Tricks
  • Frontend
  • Backend
  • Server
  • Contact
  • About
Wednesday, May 14, 2025
Adnan Halilovic Blog
  • Technologies
    • All
    • Angular
    • Git
    • JavaScript
    • ReactJS
    VS Code Setup for Angular Developers Featured Image

    Best VS Code Setup for Angular Development

    Mastering DevTools: Supercharge Your Workflow with Code Snippets!

    Mastering DevTools: Supercharge Your Workflow with Code Snippets!

    Quokka.js and Wallaby.js Giveaway

    Quokka.js and Wallaby.js Giveaway

    How to Work on Different Git Branches at the Same Time?

    How to Work on Different Git Branches at the Same Time?

    Lazyload Standalone Components in Angular

    Lazyloading Standalone Components in Angular

    Standalone Components Angular

    How to Create Standalone Components in Angular

    Private Routes in React Router V6

    Protecting Routes in React JS

    How to setup routing in ReactJS

    How to setup routing in ReactJS

    Retry Error HTTP Requests in Angular (without retryWhen)

    Retry Error HTTP Requests in Angular (without retryWhen)

  • AI Tips and Tricks
  • Frontend
  • Backend
  • Server
  • Contact
  • About
No Result
View All Result
  • Technologies
    • All
    • Angular
    • Git
    • JavaScript
    • ReactJS
    VS Code Setup for Angular Developers Featured Image

    Best VS Code Setup for Angular Development

    Mastering DevTools: Supercharge Your Workflow with Code Snippets!

    Mastering DevTools: Supercharge Your Workflow with Code Snippets!

    Quokka.js and Wallaby.js Giveaway

    Quokka.js and Wallaby.js Giveaway

    How to Work on Different Git Branches at the Same Time?

    How to Work on Different Git Branches at the Same Time?

    Lazyload Standalone Components in Angular

    Lazyloading Standalone Components in Angular

    Standalone Components Angular

    How to Create Standalone Components in Angular

    Private Routes in React Router V6

    Protecting Routes in React JS

    How to setup routing in ReactJS

    How to setup routing in ReactJS

    Retry Error HTTP Requests in Angular (without retryWhen)

    Retry Error HTTP Requests in Angular (without retryWhen)

  • AI Tips and Tricks
  • Frontend
  • Backend
  • Server
  • Contact
  • About
No Result
View All Result
Adnan Halilovic Blog
No Result
View All Result

Protecting Routes in React JS

Adnan Halilovic by Adnan Halilovic
September 7, 2022
in Frontend, JavaScript, ReactJS, Technologies
0
0
SHARES
257
VIEWS
Share on FacebookShare on Twitter
ADVERTISEMENT

Depending on your abilities or needs, protecting routes in React JS may be difficult or simple, but in this article, we’ll examine how to protect routes without difficulty.

In the previous article, we created and configured routing in React. In this article, we will expand on that project. (I strongly encourage that you read that article if you haven’t already)

How to setup routing in ReactJS – Adnan Halilovic Blog

To protect a route, I will create a new component called ProtectedRoute and wrap any component that requires protection with it. The protected route component is responsible for performing authorization and authentication checks. In the expectedRoles property, we will simply list the roles that have access to the component. Thus, the code should seem as follows:

import { Navigate } from 'react-router';
import { userRoles } from './constants';

const ProtectedRoute = ({ expectedRoles, children }) => {
  /* 
  The following constants are just `hardcoded` values that you would probably
 get from JWT or your server,  or your own logic to check wether a user
 is logged in or not, and to get the user's roles. 
 */
  const isAuthorized = true;
  const areRolesRequired = !!expectedRoles?.length;
  const roles = [userRoles.admin];

  // Checking if expected and user roles match
  const rolesMatch = areRolesRequired ? expectedRoles.some((r) => roles.indexOf(r) >= 0) : true;

  /*
 If the user is not logged in or authorized, we are just redirecting to home
 (you could add any other redirection, such as unauthorized page or anything else). 
 */
  if (!isAuthorized || !rolesMatch) {
    return <Navigate to="/" replace />;
  }

 // If the user passes all check we are returning the child component (our actual component for a route).
  return children;
};

export default ProtectedRoute;

The next step is to configure our routes-config.js file with the route configuration that we used in the previous article.

ADVERTISEMENT
import About from '../../features/about/about';
import Contact from '../../features/contact/contact';
import Home from '../../features/home/home';
import NotFound from '../../features/not-found/not-found';
import { userRoles } from './constants';
import ProtectedRoute from './protected-route';
import appRoutes from './routes';

const routesConfig = [
  {
    path: appRoutes.HOME,
    element: <Home />,
  },
  {
    path: appRoutes.ABOUT,
    element: (
      <ProtectedRoute expectedRoles={[userRoles.editor]}>
        <About />
      </ProtectedRoute>
    ),
    children: [
      {
        path: appRoutes.ABOUT_HOME,
        element: <Home />,
      },
    ],
  },
  {
    path: appRoutes.CONTACT,
    element: <Contact />,
  },
  {
    path: appRoutes.UNKNOWN,
    element: <NotFound />,
  },
];

export default routesConfig;


In addition, you may have seen the constants file containing the names of our user roles. (This is optional, but I prefer to have all the strings in separate constant files because it is better structured and you will likely make fewer mistakes and typos with this method.)

export const userRoles = {
  editor: 'Editor',
  admin: 'Admin',
  guest: 'Guest',
};

Conclusion

As you’ve seen in the post, we’ve discussed one of the options/methods for securing routes in react-router v6. This technique appeals to me because I like object-based routes and the suggested way works well with them.

ADVERTISEMENT

You can download the repo with the project from my GitHub page: adnan-halilovic/protecting-routes-in-react (github.com)

Tags: React RouterReactJSRouting
ADVERTISEMENT
Previous Post

Installing Virtualmin on Ubuntu OS

Next Post

How to Create Standalone Components in Angular

Related Posts

VS Code Setup for Angular Developers Featured Image
Angular

Best VS Code Setup for Angular Development

October 13, 2024
My Top 5 Uncommon VS Code Extensions for 2024!
Frontend

My Top 5 Uncommon VS Code Extensions for 2024!

January 27, 2024
Mastering DevTools: Supercharge Your Workflow with Code Snippets!
Frontend

Mastering DevTools: Supercharge Your Workflow with Code Snippets!

September 24, 2023
Quokka.js and Wallaby.js Giveaway
Frontend

Quokka.js and Wallaby.js Giveaway

July 26, 2023
How to Work on Different Git Branches at the Same Time?
Git

How to Work on Different Git Branches at the Same Time?

December 4, 2022
Lazyload Standalone Components in Angular
Angular

Lazyloading Standalone Components in Angular

September 11, 2022
Next Post
Standalone Components Angular

How to Create Standalone Components in Angular

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest posts

The One MCP Server Every Developer Should Be Using
AI Tips and Tricks

The One MCP Server Every Developer Should Be Using

by Adnan Halilovic
May 13, 2025
0

What Is Context 7 MCP Server? Context 7 is a Model Context Provider (MCP) server that delivers real-time documentation and metadata to...

Read moreDetails
Boosting Productivity with AI-Powered IDEs: My Workflow with Windinsurf

Boosting Productivity with AI-Powered IDEs: My Workflow with Windinsurf

May 12, 2025
Why I Switched from VS Code to Windsurf — An AI Code Editor That Changed My Workflow

Why I Switched from VS Code to Windsurf — An AI Code Editor That Changed My Workflow

May 12, 2025
The Best Coding Font to Boost Your Productivity!

The Best Coding Font to Boost Your Productivity!

October 17, 2024
VS Code Setup for Angular Developers Featured Image

Best VS Code Setup for Angular Development

October 13, 2024
Github LinkedIn Youtube Twitter Pinterest Instagram Reddit

About Me

Adnan Halilovic Blog

Adnan Halilović

Software Developer - Content Writer

I am Adnan Halilović, the man behind the website and channels that you are currently reading and viewing!

I am a software developer with over 15 years of expertise in a variety of fields.

Newsletter

Country:

Email address:


Recent from Instagram

    The Instagram Access Token is expired, Go to the Customizer > JNews : Social, Like & View > Instagram Feed Setting, to refresh it.

© 2022 Adnan Halilovic - Software development content, tips & tricks.

Click to Copy
No Result
View All Result
  • Technologies
  • AI Tips and Tricks
  • Frontend
  • Backend
  • Server
  • Contact
  • About

© 2022 Adnan Halilovic - Software development content, tips & tricks.