Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
8 replies
DennisK

Admin routes and security. How to set this up?

Hi! What is a good way of protecting admin routes? The ideal situation is, that whenever an user goes to an admin route it:

1. Does not fetch the data
2. Will get redirected back to a specific page

Right now when I throw a TRPC error, it takes a super long time until the error is shown.. It fetches like 7-8 times and returns error = null

admin route:

  getAllMembers: protectedProcedure.query(async ({ ctx }) => {
    const isAdmin = ctx.session.user.role === "admin";
    if (!isAdmin) {
      throw new TRPCError({
        code: "UNAUTHORIZED",
        message: "You are not authorized to view this page",
      });
    }
    const members = // db call

    return members;
  }),


const MembersOverview: NextPage = () => {
  const router = useRouter();
  const { data: sessionData } = useSession();

  const {
    data: members,
    isLoading,
    error,
  } = api.admin.getAllMembers.useQuery();

  // This does not really work
  if (error instanceof TRPCClientError) {
    if (error.shape.data?.code === "UNAUTHORIZED") {
      router.push("/members");
    }
  }

  return (
    <>
      <DashboardLayout profileData={sessionData?.user}>
          <Spacer size="xs" />
          {!isLoading && (
            // @ts-ignore
            <MemberDataTable columns={columns} data={members} />
          )}
      </DashboardLayout>
    </>
  );
};
Was this page helpful?