---
title: "Simple Role-Based Access Control in JavaScript"
description: "Learn how to integrate Cerbos into a JavaScript To-Do List application for robust role-based access control (RBAC). This guide covers setting up Cerbos, defining roles and permissions, and best practices for secure and scalable authorization management. Perfect for developers looking to enhance application security with fine-grained access control."
author: "Apoorv Tripathi"
date: "2025-03-17T12:38:45.996Z"
canonical: "https://www.cerbos.dev/blog/role-based-access-control-in-javascript"
image: "https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/cover_b3e59f7e6e.png"
tags: ["guide","integration","engineering"]
source: "https://www.cerbos.dev/blog/role-based-access-control-in-javascript"
---

# Simple Role-Based Access Control in JavaScript

In this tutorial, we have a To-Do List application made using HTML, CSS, and JS, and we will integrate it with Cerbos to add authorization to the app. Authorization determines if a user can perform specific actions or access certain resources or data. It enables organizations to control and secure access to sensitive databases, private and personal data, and corporate resources. In our JS application, authorization will define what actions the users can do (create a to-do and read the to-dos) and what actions the admin can do (create, read, and delete the to-dos).


### Introduction to RBAC in a JavaScript App

[Role-based access control (RBAC)](https://www.cerbos.dev/features-benefits-and-use-cases/rbac) is an [access control method](https://www.upguard.com/blog/access-control) that assigns permissions to end-users based on their organizational role. RBAC provides fine-grained control, offering a simple, manageable approach to access management that is less error-prone than individually assigning permissions. 

The advantage of using RBAC is that managing authorization privileges becomes easier because system managers can manage users and permissions in bulk instead of one by one. \
We have defined RBAC policies and will be integrating Cerbos for authorization to create, read, and delete to-dos based on who the user is. Our business requirements for who can do what are as follows:



* Admins can do all actions (create, read, and delete)
* Users can create and read to-dos but not delete a to-do.


### What is Cerbos and Why Cerbos?

Cerbos is an open-source authorization layer that enables you to easily implement authorization for your applications. At[ Cerbos](https://www.cerbos.dev/), we offer fine-grained access control to enhance security while making your application  faster and more scalable. Authorizing with Cerbos carries various advantages that are unavailable using strictly JS code



* **Greater Security**: Threats to digital infrastructure are ever-present and access management is always a pressing concern. When you have integrated Cerbos authorization in your JS app, you enable fine-grained access control and securely eliminate unauthorized access with a few lines of code.  \

* **Scalability**:  Cerbos has a centralized policy management system that is easily scalable. As the number of users in your application grows, your authorization solution will scale with your app, and the policies can be modified with a few clicks without having to change a single line of code.

<center>
<div class="hs-cta-embed hs-cta-simple-placeholder hs-cta-embed-181809013399"
  style="max-width:100%; max-height:100%; width:538px;height:267.939453125px" data-hubspot-wrapper-cta-id="181809013399">
  [![Cerbos Hub ](https://no-cache.hubspot.com/cta/default/20289770/interactive-181809013399.png)](https://cta-service-cms2.hubspot.com/web-interactives/public/v1/track/redirect?encryptedPayload=AVxigLIsPGsw0kVBfd%2BU5zXB%2F4zjrza4haEsiIWNj0lzsB%2FKVVynt63tVx41mePU0xuZZWXKK1JI6n5kTtblD%2BdJ8jxX0tmI2SlkzFmZz7o8vY%2F4oY%2FGvol3cI5tYLTx80LThtx4Ce0%2BXtshEZG1euH5uGltBdN%2FsIw6sqKALxOUiwAqfTFkXH%2Ff%2FJfG0X7u&webInteractiveContentId=181809013399&portalId=20289770)
</div>
</center>

## Best Practices for Policy Generation

When an organization adopts the RBAC access model it is imperative they adhere to best practices regarding security and administration and that they are committed to continual improvement of their access protocols to stay ahead of emerging threats. 

The following list contains some of the RBAC best practices you must follow:



1. **Identify Needs and Roles**: Understand your organization's specific needs and establish a clear hierarchy of roles. Clearly define responsibilities to guide the design of your RBAC system.
2. **Establish and Enforce Policies**: Create comprehensive RBAC policies that outline access rules, scope, and objectives, and ensure they are accessible to all stakeholders.
3. **Apply the Principle of Least Privilege**: Assign only the minimum permissions required for each role, adhering to the principle of least privilege to prevent unauthorized access.
4. **Regularly Review and Automate**: Review role assignments regularly to ensure they reflect organizational changes and use automation for efficient permission assignment and removal.
5. **Prioritize Monitoring and Response**: Implement logging and monitoring to detect suspicious behavior and develop incident response procedures to swiftly address unauthorized access.

## Modeling Policies

We will use these roles in our example code to demonstrate how access control works.

![image9.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image9_1fb4db6279.png)



With Cerbos, access rules are always resource-oriented, and the policies you write map to these resources within your system. A _resource_ can be anything, and the way you model your policies is up to you — you can achieve the same logical outcome in numerous ways: action-led, role-led, attribute-led, or with combinations thereof.

That said, some patterns will lend themselves more naturally to specific scenarios — let’s look at some different approaches. Consider this permission model:


<table>
  <tr>
   <td>Actions
   </td>
   <td colspan="5" >Roles
   </td>
  </tr>
  <tr>
   <td>
   </td>
   <td>CPO
   </td>
   <td>CTO
   </td>
   <td>Exec-1
   </td>
   <td>Exec-2
   </td>
   <td>Exec-3
   </td>
  </tr>
  <tr>
   <td>View
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
  </tr>
  <tr>
   <td>Add
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
  </tr>
  <tr>
   <td>Delete
   </td>
   <td>Allowed
   </td>
   <td>Allowed
   </td>
   <td>Not Allowed
   </td>
   <td>Not Allowed
   </td>
   <td>Not Allowed
   </td>
  </tr>
</table>


We will describe Action-led policies as we have implemented Action-led policies for our JS application.


### Action-led

Here, we focus on an action and list all the roles that can perform that action. An example from our documentation to understand this better is listed as follows:


```yaml
# Principals in the following three roles can perform the `run` action
  - actions:
      - "run"
    effect: EFFECT_ALLOW
    roles:
      - JR_MANAGER
      - SR_MANAGER
      - CFO

# All principals can perform the `view` action
  - actions:
      - "view"
    effect: EFFECT_ALLOW
    roles:
      - ["*"]
```


This approach might be suitable if any of the following apply to your system:



* Your roles are "similar" in what they can do, like JR_MANAGER and SR_MANAGER; it’s likely that JR_MANAGER will have a subset of the permissions of SR_MANAGER. There will of course be duplication in either direction, but it’s often easier to reason about this from an action perspective.
* You have "high-risk" actions — you want to be able to tell at a glance which roles have access to a particular action. The act of explicitly listing roles per action makes it much more difficult to accidentally give unwanted permissions to the wrong user.
* You have a relatively high number of roles to a low number of actions.


## Prerequisites



1. WSL (if Windows is your primary OS)
2. Docker 


## Integrating Cerbos in a JavaScript Application



1. To get started, clone [this repository](https://github.com/PrathamSikka24/todolist-cerbos) and follow along. Make sure you are in the master branch of the repository.



## File Structure of Our Application


![image13.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image13_98c0862ffc.png)



After the build is successful, you should see the web page loading on your browser at [localhost:5500](http://localhost:5500/).

![image5.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image5_4526be9adf.png)

Currently, without any policies, the CPO and CTO in this application are granted permission to delete a to-do, while the Executives(1, 2, and 3) can only view and add to-dos. However, as we have not integrated Cerbos with the application for permission management, the CTO and CPO are not able to delete the to-dos. After Cerbos is successfully integrated, the CTO and CPO will be able to DELETE the to-dos.

![image12.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image12_6ca25cd88b.png)


## Integrating Cerbos as a service

To integrate Cerbos into our JavaScript application, we will begin by launching the Cerbos Docker container. In the root directory (/to-dolist-cerbos) use the following  to run the Docker container:


```
docker run --rm --name cerbos -d -v $(pwd)/cerbos/policies:/policies -p 3592:3592 -p 3593:3593 ghcr.io/cerbos/cerbos:0.34.0 
```



## Generate Policy Files with Cerbos RBAC Policy Generator

[Cerbos Playground](https://play.cerbos.dev/) is a utility for creating and testing policies online. The Cerbos playground is a great way to learn about policy creation—and even generate usable policies:: [https://play.cerbos.dev/new?generator](https://play.cerbos.dev/new?generator). 

How to use the RBAC Policy Generator to generate a policy for our javascript application?

We have two roles: user and admin (where  CTO/CPO are the admins and executives are users). Add the actions and select checkboxes based on the permissions we want to grant. 

![image11.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image11_5ed67f3901.png)


After selecting based on preference, we can click the **Generate **button to generate a YAML policy file named _to-dos.yaml._

![image8.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image8_99f4a1de42.png)

Once you use the generator to generate a policy, just copy it and add it to your application’s file structure. The policy generator also generates a to-dos_test.yaml file, which is intended to help automate the testing of your access control policies. Ensure that the test file always ends with __test_ suffix. Here's what it typically contains and does:

![image2.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image2_dbe7a82b08.png)


Now that we have integrated Cerbos with the JS application, we will run it to check if the policies are working as expected.


## Testing Our Policy File

Let’s test the policy file with the test file and the _testdata _generated by the Cerbos RBAC Policy Generator. 

![image3.jpg](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image3_7d41bb4c53.jpg)

You can use this Docker command (in the PowerShell terminal) to run the tests: 


```
docker run -i -t -v "$(Get-Location)/cerbos/policies:/policies" ghcr.io/cerbos/cerbos:latest compile /policies
```

![image10.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image10_b001ce77cf.png)


On running this command, the tests are successfully executed. 


## Policies Taking Effect in the Application UI

If the Executives (having the role: user) try to delete a to-do: 


![image7.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image7_0de549c1a7.png)


As the policies are now being applied, executives are not allowed to delete a to-do; they get an alert: You are not authorized to delete this to-do. That privilege is only granted to CPO and CTO roles. 

As per the policy, an executive can add a to-do to the list:

![image1.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image1_9ecd42c19b.png)

Adding the task to the textbox and clicking the ADD to-do button added it to the to-do list.

![image6.png](https://stylish-appliance-1c1cc1c30d.media.strapiapp.com/image6_a6a1f2f54d.png)


The CPO was authorized, and the to-do was successfully deleted. 

This hands-on demonstration successfully depicts the integration of Cerbos with our JS application.



## Conclusion

You have successfully integrated [Cerbos](https://www.cerbos.dev/) into a demo to-do list application through the following key steps:



* We are deploying Cerbos in a Docker container to ensure a consistent and isolated environment.
* Crafting and refining policy files to define clear access control rules.
* Rebuilding the application to incorporate these policies.
* Verified that the application adheres to the established authorization rules, ensuring secure and controlled access.

## FAQ

### Why do I need RBAC in a simple JavaScript app?

Even a simple app benefits from RBAC because it controls who can do what, preventing misuse. For example, in a to-do list app, you might not want regular users deleting items they didn’t create or accessing admin-only features. RBAC provides a systematic way to enforce these rules. As your app grows (more users, more features), having RBAC from the start makes it easier to manage permissions instead of ad-hoc checks scattered in code. It keeps your app secure and your codebase cleaner.

### How can I implement RBAC in a JavaScript application?

To implement RBAC in a JavaScript app, use a library like Cerbos for centralized policy management. Define roles (such as "user" and "admin") and actions each role can perform. Set up Cerbos in a Docker container and create YAML policy files specifying each role’s permissions. Cerbos’ policy generator helps create these files quickly. Link your app with Cerbos so that, based on roles, actions like adding, reading, or deleting data are allowed or restricted. This setup keeps permissions organized and is scalable, making it easier to adjust access as your app grows.

### What libraries are best for JavaScript role-based access control?

A top library for JavaScript RBAC is Cerbos. It offers fine-grained, scalable access control with easy policy management.

However, there are many solutions available. Each suits different app scales and complexity needs.

### How do I handle dynamic permissions in JavaScript with RBAC?

To handle dynamic permissions in JavaScript with RBAC, use a policy-based library like Cerbos. Define flexible roles and permissions that can be updated in real-time without code changes. Store role permissions in a database or configuration file, then reference this data to determine user actions at runtime. Libraries like Cerbos allow dynamic policy updates, letting you scale and adjust permissions as your app evolves.

### What are some best practices we must consider while making RBAC policies?

When an organization adopts the RBAC access model, it is imperative that it adhere to best practices regarding security and administration and is committed to continual improvement of its access protocols to stay ahead of emerging threats. 

The following list contains a fair sampling of RBAC best practices:

1. Identify Needs: Understand organizational roles and responsibilities to guide RBAC design.
2. Generate a Policy: Develop a clear RBAC policy detailing rules, scope, and objectives and share it with stakeholders.
3. Establish Role Hierarchy: Define roles and responsibilities aligned with the organization's structure.
4. Apply Least Privilege: Grant minimum permissions for each role to limit access.

### Can policies be tested using Cerbos before they are live?

Yes, policies can be tested using [Cerbos](https://www.cerbos.dev/) before they are live. Cerbos provides robust policy testing capabilities, allowing you to validate your access control rules before deploying them in a production environment. Using Cerbos' testing framework available in Cerbos Policy Generator, you can ensure that policies enforce the desired access control rules and avoid potential issues in live scenarios. This pre-deployment testing helps maintain the integrity and security of your access control policies, reducing the risk of unauthorized access and ensuring compliance with your organization's security guidelines.
