How to implement redirect based on user role

Hi, I would love to implement redirections based on the user role.
I want to implement it so that on every single page, I can explicitly define which roles are allowed to view the current page and the redirect url to which the user will be redirected if he isn't authorized to view the page.
Now I have implemented a simple hook which works but the content of the page still flashes before the user gets redirected.
What is the recommended way to protect routes in t3-app based on roles?
My implementation:
useRoleRedirect.ts:
import { type Role } from "@prisma/client";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";

const useRoleRedirect = (allowedRoles: Role[], redirect: string) => {
  const userRole = useSession().data?.user.role;
  const router = useRouter();

  useEffect(() => {
    if (userRole && !allowedRoles.includes(userRole)) {
      void router.push(redirect);
    }
  }, [router, userRole, redirect, allowedRoles]);
};

export default useRoleRedirect;

Usage of hook in other component:
const Page: NextPage = () => {
  useRoleRedirect([Role.ADMIN, Role.MANAGER], "/");
...

Now this thing works but the original content from "Page" still gets flashed which I would like to prevent.
I'm also just curious what the standard way of handling this type of problem is.
I greatly appreciate any advice 🙂
Was this page helpful?