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
"use client";

import { PropsWithChildren } from "react";
import useAuth from "hooks/useAuth";
import ErrorView from "page-sections/permission/ErrorView";

const RoleBasedGuard = ({ children, roles = [] }) => {
const { user } = useAuth();

const loggedInUserRole = user?.role;

if (loggedInUserRole && roles.includes(loggedInUserRole)) {
return <>{children}</>;
}

return <ErrorView />;
};

export default RoleBasedGuard;
layout.jsx
import { RoleBasedGuard } from "components/auth";

const AuthLayout = ({ children }) => {
return (
<RoleBasedGuard roles={["editor", "administrator", "admin"]}>
{children}
</RoleBasedGuard>
);
};

export default AuthLayout;
Last updated on