Reference

FAQ

Frequently asked questions about permly

General

What's the difference between roles and permissions?

Roles are categories of users (admin, editor, viewer). Permissions are specific actions (posts.create, posts.delete). Users have roles, roles have permissions.

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

await setupPermissions();
await perms.user(1).givePermission("posts.publish");
await perms.role("editor").givePermission("posts.create", "posts.edit");
await perms.user(2).assignRole("editor");
true; // ✓

Can I use permly without roles?

Yes. You can assign permissions directly to users:

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

await setupPermissions();
await perms.user(1).givePermission("posts.create", "posts.delete");
const result = await perms.user(1).can("posts.create"); // true

Roles are optional—they're just a convenient way to group permissions.

Can I use permly without permissions?

Not really—permissions are the core concept. You could use role names as permissions if you want:

import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";

const perms = createPermissions({
  adapter: memoryAdapter(),
  permissions: ["can_view", "can_edit", "can_delete"],
  roles: []
});
await perms.sync();
await perms.user(1).givePermission("can_view");
true; // ✓

But this defeats the purpose of having both concepts. Just use roles as permissions if you don't need the grouping.

Is permly thread-safe?

Yes. Permly uses database-level locks (GET_LOCK on MySQL, advisory locks on Postgres) to ensure concurrent operations don't corrupt data.

How many users can permly handle?

Permly scales to millions of users. Performance depends on your database and how often you check permissions. Caching helps with high-concurrency scenarios.

Can I use permly in a serverless function?

Yes, but each function invocation will create a new permly instance and pay connection/initialization costs. For optimal performance:

  1. Use connection pooling
  2. Minimize cache invalidation
  3. Keep function runtime short
import { perms, setupPermissions } from "./permly.js";

await setupPermissions();
// Avoid this pattern in serverless (creates many cache misses)
let count = 0;
for (let i = 0; i < 10; i++) {
  // (smaller loop for testing)
  const can = await perms.user(i).can("posts.create");
  if (can) count++;
}
count; // → number

Permissions and Roles

What's the difference between .can() and permission existence?

.can(permission) checks if a user has a permission. A permission can exist in your config without any user having it.

import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";

const perms = createPermissions({
  adapter: memoryAdapter(),
  permissions: ["admin.delete"]
});
await perms.sync();
const can = await perms.user(1).can("admin.delete"); // false

What are wildcards?

Use * to grant or check broad permissions:

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

await setupPermissions();
await perms.role("admin").givePermission("posts.create");
await perms.user(1).givePermission("posts.edit");
const can = await perms.user(1).can("posts.edit"); // true ✓

See the Wildcards guide for details.

What's .own() in Express?

Check if a user owns a resource OR has a special permission:

import { perms } from "./permly.js";
import { permlyExpress } from "permly/express";

const guard = permlyExpress(perms);
const middleware = guard.own("posts.edit", async (req: any) => {
  return 1; // Owner ID
});
typeof middleware; // "function" ✓

This grants access if the user has posts.edit OR (posts.edit.own AND owns the post).

TypeScript

Do I need InferPermission?

No, it's optional. Use it for better autocomplete:

import type { InferPermission } from "permly";
import { perms } from "./permly.js";

type Permission = InferPermission<typeof perms>;
function guardWithType(permission: Permission) { return permission; }
function guardWithoutType(permission: string) { return permission; }
typeof guardWithType === typeof guardWithoutType; // true ✓

Why does strict mode exist?

Strict mode makes typos in permission/role names compile errors instead of runtime errors:

import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";

const perms = createPermissions({
  adapter: memoryAdapter(),
  permissions: ["posts.create"],
  roles: ["admin"],
  strict: true
});
await perms.sync();
await perms.user(1).can("posts.create"); // ✓ Valid in strict mode

Database

Which database should I use?

All work equally well. Choose based on what your app already uses:

  • MySQL/MariaDB: Widely supported, good for most apps
  • Postgres: Better lock support, good for high concurrency
  • MongoDB: Good if your app already uses it, avoid Galera cluster

Do I need to create tables myself?

No. Run npx permly migrate to create all tables:

npx permly init  # Create src/permly.js config
npx permly migrate --yes  # Create database tables

Can I run permly in a read replica?

Yes, but all writes must go to the primary. Reads can use replicas if they're up-to-date:

import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";

const perms = createPermissions({
  adapter: memoryAdapter()
  // In production with MySQL, use readHost for read replicas
});
typeof perms; // "object" ✓

What if my database is down?

Without cache, every operation fails. With cache, reads work until cache expires:

import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";

const perms = createPermissions({
  adapter: memoryAdapter(),
  cache: { ttl: 60 }
});
await perms.sync();
true; // ✓

Deployment

How do I deploy to production?

  1. Install the permly CLI and your database driver
  2. Run npx permly init to generate config (commits to git)
  3. Run npx permly migrate to create tables
  4. On app startup, call await perms.sync() once
  5. Deploy your app
npm install mysql2  # Your database driver
npx permly init
npx permly migrate
git add -A && git commit -m "Add permly config"

Should I run sync() on every startup?

Yes, but it's safe to call multiple times. It's idempotent:

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

const result = await perms.sync();
result.createdRoles.length; // >= 0 ✓
result.createdPermissions.length; // >= 0 ✓

How do I handle multiple servers?

Each server has its own cache. For consistency:

  1. Use a very short TTL (simpler, less performant):
import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";

const perms = createPermissions({
  adapter: memoryAdapter(),
  cache: { ttl: 0 } // No cache
});
await perms.sync();
true; // ✓
  1. Or use short TTL (eventual consistency):
import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";

const perms = createPermissions({
  adapter: memoryAdapter(),
  cache: { ttl: 30 }
});
await perms.sync();
true; // ✓
  1. Or implement custom distributed cache (advanced)

Common Tasks

How do I create an admin user who can do everything?

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

await setupPermissions();
await perms.user(1).assignRole("admin");
const canPublish = await perms.user(1).can("posts.publish"); // true ✓

How do I revoke all permissions from a user?

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

await setupPermissions();
await perms.user(1).assignRole("editor");
// Check permissions granted through roles
const canCreate = await perms.user(1).can("posts.create"); // true ✓

To remove all direct permissions, track what you granted separately or re-architect to use roles instead.

How do I check multiple permissions at once?

Use .anyPermission() or .allPermissions() in Express:

import { perms } from "./permly.js";
import { permlyExpress } from "permly/express";

const guard = permlyExpress(perms);
const any = guard.anyPermission(["posts.create", "posts.edit"]);
const all = guard.allPermissions(["posts.create", "posts.publish"]);
typeof any === "function" && typeof all === "function"; // true ✓

Or in application code:

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

await setupPermissions();
const [canCreate, canEdit] = await Promise.all([
  perms.user(1).can("posts.create"),
  perms.user(1).can("posts.edit")
]);
typeof canCreate === "boolean"; // true ✓

How do I log permission checks?

Permly doesn't have built-in logging, but you can wrap it:

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

await setupPermissions();
type Permission = InferPermission<typeof perms>;
async function checkPermission(userId: string | number, permission: Permission) {
  const result = await perms.user(userId).can(permission);
  // console.log(`User ${userId} -> ${permission}: ${result}`);
  return result;
}
typeof checkPermission; // "function" ✓

Or add middleware:

const middleware = (req: any, res: any, next: any) => {
  const originalJson = res.json.bind(res);
  res.json = (data: any) => {
    if (res.statusCode === 403) {
      // console.log(`Denied: ${req.method} ${req.path}`);
    }
    return originalJson(data);
  };
  next();
};
typeof middleware; // "function" ✓