Permix

Express

Learn how to use Permix with Express

Overview

Permix provides middleware for Express that allows you to easily check permissions in your routes. The middleware can be created using the createPermix function.

Before getting started with Express integration, make sure you've completed the initial setup steps in the Quick Start guide.

Setup

Here's a basic example of how to use the Permix middleware with Express:

import  from 'express'
import {  } from 'permix/express'
 
interface Post {
  : string
  : string
  : string
  : string
}
 
// Initialize Express
const  = ()
 
// Create your Permix instance
const  = <{
  : {
    : Post
    : 'create' | 'read' | 'update'
  }
}>()
 
// Set up the middleware with your permission rules
.(.(({  }) => {
  // You can access req.user or other properties to determine permissions
  return {
    : {
      : true,
      : true,
      : false
    }
  }
}))

The middleware preserves full type safety from your Permix definition, ensuring your permission checks are type-safe.

Checking Permissions

Use the checkMiddleware function in your Express routes to check permissions:

app.post('/posts', permix.checkMiddleware('post', 'create'), (req, res) => {
  res.json({ success: true })
})
 
// Check multiple actions
app.put('/posts/:id', permix.checkMiddleware('post', ['read', 'update']), (req, res) => {
  res.json({ success: true })
})
 
// Check all actions
app.delete('/posts/:id', permix.checkMiddleware('post', 'all'), (req, res) => {
  res.json({ success: true })
})

Accessing Permix Directly

You can access the Permix instance directly in your route handlers using the get function:

app.get('/posts', (req, res) => {
  const { check } = permix.get(req, res)
 
  // Check permissions manually
  if (check('post', 'read')) {
    // User has permission to read posts
    res.json({ posts: getAllPosts() })
  } else {
    res.status(403).json({ error: 'You do not have permission to read posts' })
  }
})

The get function returns the Permix instance with available methods.

Using Templates

Permix provides a template helper to create reusable permission rule sets:

// Create a template for admin permissions
const adminTemplate = permix.template({
  post: {
    create: true,
    read: true,
    update: true
  }
})
 
// Use the template in your middleware
app.use(permix.setupMiddleware(({ req }) => {
  // You can still customize the template based on request data
  if (req.user?.role === 'admin') {
    return adminTemplate
  }
 
  return {
    post: {
      create: false,
      read: true,
      update: false
    }
  }
}))

Custom Error Handling

By default, the middleware returns a 403 Forbidden response. You can customize this behavior by providing an onForbidden handler:

Basic Error Handler

const permix = createPermix<Definition>({
  onForbidden: ({ res }) => {
    res.status(403).json({
      error: 'Custom forbidden message',
    })
  }
})

Dynamic Error Handler

You can also provide a handler that returns different responses based on the entity and actions:

const permix = createPermix<Definition>({
  onForbidden: ({ res, entity, actions }) => {
    if (entity === 'post' && actions.includes('create')) {
      res.status(403).json({
        error: `You don't have permission to ${actions.join('/')} a ${entity}`,
      })
      return
    }
 
    res.status(403).json({
      error: 'You do not have permission to perform this action',
    })
  }
})

The onForbidden handler receives:

  • req: Express Request object
  • res: Express Response object
  • entity: The entity that was checked
  • actions: Array of actions that were checked

Advanced Usage

Async Permission Rules

You can use async functions in your permission setup:

app.use(permix.setupMiddleware(async ({ req }) => {
  // Fetch user permissions from database
  const userPermissions = await getUserPermissions(req.user.id)
 
  return {
    post: {
      create: userPermissions.canCreatePosts,
      read: userPermissions.canReadPosts,
      update: userPermissions.canUpdatePosts
    }
  }
}))

Dynamic Data-Based Permissions

You can check permissions based on the specific data being accessed:

app.put('/posts/:id', async (req, res, next) => {
  const post = await getPostById(req.params.id)
 
  const { check } = permix.get(req, res)
 
  // Check if user can update this specific post
  if (check('post', 'update', post)) {
    next()
  } else {
    res.status(403).json({ error: 'You cannot update this post' })
  }
})

On this page