Route Guard
Role Based Guard
For NextJS

How to work it ?

Sometime we have a list of routes for specific user roles, such as admin, user, editor, etc. In this case, we want to show the role based routes permission then we can use RoleBasedGuard component from app.

RoleBasedGuard.jsx

_19
"use client";
_19
_19
import { PropsWithChildren } from "react";
_19
import useAuth from "hooks/useAuth";
_19
import ErrorView from "page-sections/permission/ErrorView";
_19
_19
const RoleBasedGuard = ({ children, roles = [] }) => {
_19
const { user } = useAuth();
_19
_19
const loggedInUserRole = user?.role;
_19
_19
if (loggedInUserRole && roles.includes(loggedInUserRole)) {
_19
return <>{children}</>;
_19
}
_19
_19
return <ErrorView />;
_19
};
_19
_19
export default RoleBasedGuard;

layout.jsx

_11
import { RoleBasedGuard } from "components/auth";
_11
_11
const AuthLayout = ({ children }) => {
_11
return (
_11
<RoleBasedGuard roles={["editor", "administrator", "admin"]}>
_11
{children}
_11
</RoleBasedGuard>
_11
);
_11
};
_11
_11
export default AuthLayout;