tRPC
Learn how to use Permix with tRPC
Overview
Permix provides a middleware for tRPC that allows you to easily check permissions in your procedures. The middleware can be created using the createPermix
function.
Before getting started with tRPC 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 tRPC:
The middleware preserves the context and input types from your tRPC procedures, ensuring end-to-end type safety in your API.
Accessing Permix in Procedures
Permix is automatically added to your tRPC context, so you can access it directly:
The ctx.permix
object contains two methods:
check
: Synchronously check a permissioncheckAsync
: Asynchronously check a permission
Custom Error Handling
By default, the middleware throws a TRPCError
with code FORBIDDEN
. You can customize this behavior by providing a forbiddenError
option:
Static Error
Dynamic Error
You can also provide a function that returns different errors based on the entity and actions:
The forbiddenError
handler receives:
ctx
: Your tRPC context 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: