Implementing Role-Based Access Control (RBAC) in Next.js

Amit Kumar
2 min readJun 22, 2023

--

Role-Based Access Control (RBAC) is a widely used authorisation mechanism in web applications to manage user permissions and access control. In this article, we will explore how to implement RBAC in a Next.js application, ensuring that certain components or routes are accessible only to users with specific roles or permissions. We will leverage the Next.js framework and React Redux for state management. Let’s dive into the implementation.

Implementation

To implement RBAC in Next.js, we will define a higher-order component (HOC) called withRoles. This HOC will wrap around components that require specific roles or permissions. Here's the code for the withRoles function

import { useRouter } from 'next/router'
import { ROUTES } from 'src/shared'

function hasRequiredPermissions(requiredPermissions: string[]): boolean {
// get userPermissions from the redux-store
const userPermissions = ['users', 'groups', 'home']
return requiredPermissions.some((permission) =>
userPermissions.includes(permission)
)
}

export function withRoles(Component: any, requiredPermissions: string[]) {
return function WithRolesWrapper(props: any) {
const router = useRouter()
const hasPermission = hasRequiredPermissions(requiredPermissions)
if (hasPermission) {
return <Component {...props} />
} else {
router.push(ROUTES.DASHBOARD)
return null
}
}
}

for more scalable approach you can get userPermissions array from the redux-store instead of hard code it.

Usage

import styles from './styles.module.css'
import { Box } from '@mui/system'

const UsersList = () => {
return (
<Box className={styles.usersList}>
usersList
</Box>
)
}

export default withRoles(UsersList, ['users'])

In this example, the UsersList component is wrapped with the withRoles HOC. The second argument of withRoles is an array of required permissions, in this case, ['users']. Only users with the 'users' permission will be able to access the UsersList component. If a user without the required permission attempts to access the component, they will be redirected to the dashboard route specified in ROUTES.DASHBOARD.

Conclusion

Implementing Role-Based Access Control (RBAC) in a Next.js application provides a robust way to manage user permissions and restrict access to certain components or routes. By using the withRoles higher-order component, we can easily wrap components with the necessary permission checks. This approach ensures that unauthorised users are redirected appropriately, enhancing the security and control of our application.

Remember to adapt the code to fit your specific RBAC implementation and modify the permissions logic as per your application’s requirements. With this RBAC implementation.

--

--

Amit Kumar
Amit Kumar

Written by Amit Kumar

Make it work, Make it right, Make it fast.

No responses yet