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;
}),
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>
</>
);
};
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>
</>
);
};
4 Replies
JulieCezar
JulieCezar•15mo ago
from the creator of tRPC
JulieCezar
JulieCezar•15mo ago
No description
JulieCezar
JulieCezar•15mo ago
So no... this what you have is the best you can do with trpc However, you can make it so that the whole page shouldn't be accessed by user's other than the admin you should check if the user is an admin when he comes to the page, and if he isn't redirect him then no need to wait untill api call
DennisK
DennisK•15mo ago
Ok thanks 🙂
Want results from more Discord servers?
Add your server