Admin authentication

hey i added ADMIN role to some users and i am creating an admin panel. for every path staring with /admin i want only admins to access it. how can i do it?
2 Replies
TimTim
TimTim7d ago
You can check their role at the level of the page you want to display only to admin role users. If they're not an admin, redirect them to another page. Something like this
const ProtectedPage = () => {
const { data: session, status } = useSession();
const router = useRouter();

// If session is loading, display a loading indicator
if (status === "loading") {
return <p>Loading...</p>;
}

// If there's no session or the user role is not "user", redirect to unauthorized
if (!session || session.user?.role !== "user") {
router.push("/unauthorized");
return null; // Prevents rendering protected content
}

return (
<div>
<h1>Welcome to the Protected Page</h1>
<p>Your role: {session.user.role}</p>
</div>
);
};
const ProtectedPage = () => {
const { data: session, status } = useSession();
const router = useRouter();

// If session is loading, display a loading indicator
if (status === "loading") {
return <p>Loading...</p>;
}

// If there's no session or the user role is not "user", redirect to unauthorized
if (!session || session.user?.role !== "user") {
router.push("/unauthorized");
return null; // Prevents rendering protected content
}

return (
<div>
<h1>Welcome to the Protected Page</h1>
<p>Your role: {session.user.role}</p>
</div>
);
};
OreQr
OreQr7d ago
@şiar_619 If you want to do this TimTim way on server side layout, remember to add additional check on every children page or you gonna leak data.

Did you find this page helpful?