Home > Enterprise >  React Prevent routing while user manually changes url in the browser
React Prevent routing while user manually changes url in the browser

Time:02-01


const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
  },
  {
    path: "/main",
    element: (
      <AdminAuth redirectTo="/profile">
        <Main />
      </AdminAuth>
    ),
  },])
import React from "react";

import { Link, Navigate } from "react-router-dom";
import { isAutheticated } from "../auth";

export const AdminAuth = ({ children, redirectTo }) => {
  let auth = isAutheticated().user_Role;
  return auth === "admin" ? children : <Navigate to={redirectTo} />;
};

i want to Prevent routing while user manually changes url in the browser. i got the /main as a admin route, which i'm protecting but the issue starts when user changes his role in the local storage and try to access /main. so i want to prevent user from manually changing the route in their url or show error if they change manually.

EDIT: i'm protecting my route in the backend, but in the frontend i don't user to even access this.

CodePudding user response:

Considering that all code on the client can be changed by the user, setting up protected routes like yours, should only be for a better user experience. You cannot and should not depend on client logic to protect data from non-admin users. This has to be done on the backend/server.

Therefore, using local storage as your business logic for identifying an admin user or not, would be highly critical, since everyone could change that. Instead it should be done by some token, for exmaple JWT (Json Web Token) using a authentication provider like AWS Cognito or similiar, or even building your own server side authetication logic.

CodePudding user response:

Simply by sending prop from previous page, you can control and simply send the user back to the proper page.

  • Related