Node.js
Learn how to use Permix with Node.js HTTP servers
Overview
Permix provides middleware for Node.js HTTP servers that allows you to easily check permissions in your request handlers. The middleware can be created using the createPermix
function.
Before getting started with Node.js 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 a Node.js HTTP server:
The middleware preserves full type safety from your Permix definition, ensuring your permission checks are type-safe.
Accessing Permix Directly
You can access the Permix instance directly in your request handlers using the get
function:
The get
function returns the Permix instance with available methods.
Custom Error Handling
By default, the middleware returns a 403 Forbidden response if the user doesn't have permission. You can customize this behavior by providing an onForbidden
handler:
Basic Error Handler
Dynamic Error Handler
You can also provide a handler that returns different responses based on the entity and actions:
The onForbidden
handler receives:
req
: Node.js IncomingMessage objectres
: Node.js ServerResponse objectentity
: The entity that was checkedactions
: Array of actions that were checked
Advanced Usage
Async Permission Rules
You can use async functions in your permission setup:
Dynamic Data-Based Permissions
You can check permissions based on the specific data being accessed:
Integration with Web Frameworks
This integration is designed for raw Node.js HTTP servers. If you're using a web framework:
- For Express, use Permix Express integration
- For Hono, use Permix Hono integration