Role-based access patterns help control who can see or do what in your app. They keep your app safe and organized by giving different users different permissions.
0
0
Role-based access patterns in NextJS
Introduction
When you want to show different pages or features to admins and regular users.
When you need to protect sensitive data from unauthorized users.
When you want to simplify user experience by hiding options users shouldn't access.
When building apps with multiple user types like customers, staff, and managers.
Syntax
NextJS
import { useSession } from 'next-auth/react'; export default function Page() { const { data: session } = useSession(); if (!session) { return <p>Please log in to view this page.</p>; } if (session.user.role !== 'admin') { return <p>Access denied. Admins only.</p>; } return <p>Welcome, admin!</p>; }
Use useSession from next-auth/react to get user info.
Check the user's role from the session object to control access.
Examples
Simple check to show different content based on role.
NextJS
if (session.user.role === 'admin') { // show admin content } else { // show regular user content }
Check if user role is in a list of allowed roles.
NextJS
const allowedRoles = ['admin', 'manager']; if (allowedRoles.includes(session.user.role)) { // allow access } else { // deny access }
Higher-order component to wrap pages or components with role checks.
NextJS
import { useSession } from 'next-auth/react'; export function withRole(Component, allowedRoles) { return function WrappedComponent(props) { const { data: session } = useSession(); if (!session || !allowedRoles.includes(session.user.role)) { return <p>Access denied.</p>; } return <Component {...props} />; }; }
Sample Program
This component shows different messages based on the user's role from the session. It handles three roles: admin, editor, and viewer. If the user is not logged in, it asks them to log in.
NextJS
import { useSession } from 'next-auth/react'; export default function Dashboard() { const { data: session } = useSession(); if (!session) { return <p>Please log in to access the dashboard.</p>; } switch (session.user.role) { case 'admin': return <p>Welcome Admin! You can manage users and settings.</p>; case 'editor': return <p>Welcome Editor! You can edit content.</p>; case 'viewer': return <p>Welcome Viewer! You can view content only.</p>; default: return <p>Role not recognized. Access limited.</p>; } }
OutputSuccess
Important Notes
Always check if the user is logged in before checking roles.
Store user roles securely and avoid trusting client-side data alone.
Use server-side checks for sensitive data or actions to improve security.
Summary
Role-based access controls who can see or do things in your app.
Use session data to check user roles and show or hide content accordingly.
Protect sensitive parts of your app by restricting access based on roles.