Guides

Roles

Group permissions together and assign them to users

What it does

A role is a named group of permissions. Instead of assigning permissions one by one, you create a role (like editor) and give it multiple permissions at once. Users get roles, and those roles give them all the permissions in that group.

When to use it

Use roles when you have:

  • Groups of users with the same access level (admins, editors, viewers)
  • Stable permission sets (e.g., all editors can create and edit posts)
  • Multiple permissions per user (assigning each one individually would be tedious)

If you have just one or two permissions and users rarely overlap, use direct permissions instead.

How it works

  1. Define roles in config: ["admin", "editor", "viewer"]
  2. Grant permissions to each role: admin gets *, editor gets posts.create and posts.edit
  3. Assign roles to users: await perms.user(1).assignRole("editor")
  4. Users get all permissions from that role automatically

When a user checks a permission, permly looks up their roles and checks all permissions in those roles.

Examples

import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

// Assign a role to a user
await perms.user(42).assignRole("editor");

// User now has all permissions granted to the editor role
const canCreate = await perms.user(42).can("posts.create");
console.log(canCreate); // true (if editor has posts.create)
import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

await perms.user(42).assignRole("editor");

const canCreate: boolean = await perms.user(42).can("posts.create");
console.log(canCreate);

Users can have multiple roles

A user can belong to more than one role. Their permissions are the union of all their roles:

import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

// User has both editor and moderator roles
await perms.user(42).assignRole("editor");
await perms.user(42).assignRole("moderator");

// User can do anything an editor OR moderator can do
const canDelete = await perms.user(42).can("comments.delete");
console.log(canDelete); // true (if either role has it)
import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

await perms.user(42).assignRole("editor");
await perms.user(42).assignRole("moderator");

const canDelete: boolean = await perms.user(42).can("comments.delete");
console.log(canDelete);

Common mistakes

Assigning the same role twice — It's harmless; the second assignment does nothing. But check for duplicates in your UI.

Forgetting to grant permissions to the role — Create a role but forget to give it any permissions? Users with that role can't do anything. Always check your role config.

Confusing roles with permissions — A role is a container. A permission is what the role grants. Don't mix them up in your mental model.