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 thesetupmethod orhydrate().ready- Triggered once when the instance first becomes ready (firstsetup(), or initial rules passed tocreatePermix). Latersetup()calls do not firereadyagain.hydrate()alone does not triggerready.check- Triggered every timecheck()is called. The handler receives a context object withpathanddata.
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