Permix

Events

Learn how to handle permission updates in your application

Overview

Permix provides an event system that allows you to react to permission changes in your application. Each event provides type-safe data and hooks to register handlers.

Usage

You can register event handlers using the hook and hookOnce methods:

const permix = createPermix<{
  post: ['create', 'read']
}>()

// The handler will be called every time setup is executed
permix.hook('setup', () => {
  console.log('Permissions were updated')
})

// The handler will be called only once
permix.hookOnce('setup', () => {
  console.log('Permissions were updated once')
})

// Calling `setup` triggers the `setup` event
// and `ready` on the first successful setup
permix.setup({
  post: {
    create: true,
    read: true
  }
})

Available events:

  • setup - Triggered when permissions are updated through the setup method or hydrate().
  • ready - Triggered once when the instance first becomes ready (first setup(), or initial rules passed to createPermix). Later setup() calls do not fire ready again. hydrate() alone does not trigger ready.
  • check - Triggered every time check() is called. The handler receives a context object with path and data.

Use the setup event when UI or caches should refresh after every permission change. Use ready only for one-time bootstrap (for example, hiding a global loading shell). Use check for logging, analytics, or debugging permission evaluations.

Check Event

The check event fires before every permission evaluation and provides the path and data being checked:

const permix = createPermix<{
  post: ['create', { name: 'edit', type: { authorId: string }, required: true }]
}>()

permix.hook('check', ({ path, data }) => {
  console.log(`Checking permission: ${path}`, data)
})

permix.setup({
  post: {
    create: true,
    edit: (post) => post.authorId === currentUserId,
  },
})

permix.check('post.create')
// logs: Checking permission: post.create undefined

permix.check('post.edit', { authorId: '1' })
// logs: Checking permission: post.edit { authorId: '1' }

When using the callback form of check(), path will be null:

permix.check(c => c('post.create') && c('post.edit', { authorId: '1' }))
// logs: Checking permission: null undefined

On this page