Express.js integration for Autorix policy-based authorization (RBAC + ABAC)
npm install @autorix/expressExpress.js integration for Autorix policy-based authorization (RBAC + ABAC)
Middleware and utilities to integrate Autorix authorization into your Express.js applications with a clean, flexible API.


- 🛡️ Middleware-based - Simple Express.js middleware integration
- 🎯 Route-level Authorization - Protect specific routes with the authorize middleware
- 🔄 Request Context - Automatic context building from Express requests
- 💪 Flexible Principal Resolution - Custom logic for extracting user information
- 🏢 Multi-tenant Support - Built-in tenant isolation
- 📦 Resource Loading - Automatic resource resolution from route parameters
- 🚀 TypeScript Ready - Full type safety with Express types augmentation
- ⚡ Zero Config - Works out of the box with sensible defaults
``bash`
npm install @autorix/express @autorix/core @autorix/storageor
pnpm add @autorix/express @autorix/core @autorix/storageor
yarn add @autorix/express @autorix/core @autorix/storage
`typescript
import express from 'express';
import { autorixExpress, authorize, autorixErrorHandler } from '@autorix/express';
import { evaluateAll } from '@autorix/core';
import { MemoryPolicyProvider } from '@autorix/storage';
const app = express();
app.use(express.json());
// Initialize policy provider
const policyProvider = new MemoryPolicyProvider();
// Create enforcer
const enforcer = {
can: async (input: { action: string; resource: string; context: any }) => {
// ✅ IMPORTANT: If your app allows unauthenticated requests, guard here
// to avoid storage/providers crashing when principal is null.
if (!input.context?.principal) {
return { allowed: false, reason: 'Unauthenticated' };
}
const policies = await policyProvider.getPolicies({
scope: input.context.tenantId || 'default',
principal: input.context.principal,
roleIds: input.context.principal?.roles,
});
const result = evaluateAll({
policies: policies.map(p => p.document),
action: input.action,
resource: input.resource, // ← String for matching (e.g., 'post/123')
ctx: input.context, // ← Contains resource object in ctx.resource
});
return { allowed: result.allowed, reason: result.reason };
}
};
// Add the Autorix middleware (must be registered before routes)
app.use(autorixExpress({
enforcer,
getPrincipal: async (req) => {
// Extract user from your auth middleware (e.g., JWT/Passport/session)
return req.user ? { id: req.user.id, roles: req.user.roles } : null;
},
getTenant: async (req) => {
// Extract tenant/organization ID
return req.user?.tenantId || null;
}
}));
// Protect routes with authorize middleware
app.get(
'/admin/users',
authorize('user:list', { requireAuth: true }),
(req, res) => {
res.json({ message: 'Authorized!' });
}
);
app.delete(
'/posts/:id',
authorize({
action: 'post:delete',
requireAuth: true,
resource: {
type: 'post',
idFrom: (req) => req.params.id,
loader: async (id) => await db.posts.findById(id),
}
}),
(req, res) => {
res.json({ message: 'Post deleted!' });
}
);
// ✅ IMPORTANT: Register Autorix error handler at the end
// so authorization errors return clean HTTP responses (401/403) instead of stack traces.
app.use(autorixErrorHandler());
app.listen(3000);
`
Main middleware that initializes Autorix on the Express request object.
#### Options
`typescript`
type AutorixExpressOptions = {
enforcer: {
can: (input: {
action: string;
context: AutorixRequestContext;
resource?: unknown;
}) => Promise<{ allowed: boolean; reason?: string }>;
};
getPrincipal: (req: Request) => Principal | Promise
getTenant?: (req: Request) => string | null | Promise
getContext?: (req: Request) => Partial
onDecision?: (decision: { allowed: boolean; action: string; reason?: string }, req: Request) => void;
};
- enforcer: The Autorix instance or compatible enforcer
- getPrincipal: Function to extract user/principal information from the request
- getTenant (optional): Function to extract tenant/organization ID
- getContext (optional): Additional context builder (IP, user agent, custom attributes)
- onDecision (optional): Callback for logging/auditing authorization decisions
#### Request Augmentation
After this middleware runs, req.autorix is available with:
`typescript`
req.autorix = {
context: AutorixRequestContext,
can: (action: string, resource?: unknown, ctxExtra?: Record
enforce: (action: string, resource?: unknown, ctxExtra?: Record
}
Route-level middleware for authorization checks.
#### Simple Usage
`typescript`
app.get('/users', authorize('user:list'), handler);
#### Advanced Usage
`typescript`
authorize({
action: string;
resource?: ResourceSpec;
context?: Record
requireAuth?: boolean;
})
- action: The action to authorize (e.g., 'user:read', 'post:delete')resource
- (optional): Resource specificationtype
- String: Static resource identifier
- Object with , id, data: Static resource objecttype
- Object with , idFrom, loader: Dynamic resource loadingcontext
- (optional): Additional context attributes or function to compute themrequireAuth
- (optional): Whether to require authenticated principal (throws AutorixUnauthenticatedError if not present)
#### Resource Specification
`typescript
// Static resource
authorize({ action: 'post:read', resource: 'post/123' })
// Resource from route params
authorize({
action: 'post:delete',
resource: {
type: 'post',
idFrom: (req) => req.params.id,
loader: async (id, req) => await db.posts.findById(id)
}
})
// Pre-loaded resource
authorize({
action: 'user:update',
resource: { type: 'user', id: '123', data: { ownerId: 'u1' } }
})
`
Autorix uses two separate concepts for resources:
1. Resource String (for pattern matching in policies)
- Format: type/id or type/*Resource
- Used in policy field'post/123'
- Example: , 'document/*'
2. Resource Object (for attribute-based conditions)
- Contains resource properties/attributes
- Used in policy Condition blocks{ type: 'post', id: '123', authorId: 'u1' }
- Example:
How they work together:
`typescript
// Policy matches by string pattern
Statement: [{
Effect: 'Allow',
Action: ['post:delete'],
Resource: 'post/*', // ← Matches 'post/123'
Condition: {
StringEquals: {
'resource.authorId': '${principal.id}' // ← Uses resource object
}
}
}]
// Middleware automatically handles both
authorize({
action: 'post:delete',
resource: {
type: 'post',
idFrom: (req) => req.params.id, // → Builds string: 'post/123'
loader: async (id) => {
const post = await db.posts.findById(id);
return { authorId: post.authorId }; // → Object for conditions
}
}
})
`
`typescript
import { autorixExpress, authorize } from '@autorix/express';
import { Autorix } from '@autorix/core';
import { MemoryPolicyProvider } from '@autorix/storage';
const provider = new MemoryPolicyProvider();
const autorix = new Autorix(provider);
// Add policies
await provider.attachPolicy({
scope: { type: 'TENANT', id: 't1' },
policyId: 'admin-policy',
principals: [{ type: 'ROLE', id: 'admin' }]
});
await provider.setPolicy('admin-policy', {
Version: '2024-01-01',
Statement: [{
Effect: 'Allow',
Action: ['*'],
Resource: ['*']
}]
});
app.use(autorixExpress({
enforcer: autorix,
getPrincipal: (req) => req.user || null,
getTenant: (req) => req.user?.tenantId || 't1'
}));
// Only admins can access
app.get('/admin/settings',
authorize('admin:settings:read'),
(req, res) => res.json({ settings: {} })
);
`
`typescript
// Policy with conditions - checks resource attributes
await provider.setPolicy('owner-only', {
Version: '2024-01-01',
Statement: [{
Effect: 'Allow',
Action: ['post:update', 'post:delete'],
Resource: ['post/*'], // ← Matches 'post/123' string pattern
Condition: {
StringEquals: {
'resource.authorId': '${principal.id}' // ← Checks resource object property
}
}
}]
});
// Route with resource loading
app.put('/posts/:id',
authorize({
action: 'post:update',
resource: {
type: 'post',
idFrom: (req) => req.params.id,
loader: async (id) => {
const post = await db.posts.findById(id);
// Return object with properties for conditions
return {
authorId: post.authorId, // ← This becomes resource.authorId in conditions
status: post.status
};
}
}
}),
(req, res) => {
// Only post author can update
res.json({ message: 'Post updated!' });
}
);
`
`typescript
app.use(autorixExpress({
enforcer: autorix,
getPrincipal: (req) => req.user,
getContext: (req) => ({
ip: req.ip,
userAgent: req.get('user-agent'),
requestId: req.id,
attributes: {
timeOfDay: new Date().getHours(),
department: req.user?.department
}
})
}));
// Policy can check custom attributes
await provider.setPolicy('business-hours', {
Version: '2024-01-01',
Statement: [{
Effect: 'Allow',
Action: ['report:generate'],
Resource: ['*'],
Condition: {
NumericGreaterThanEquals: { 'context.attributes.timeOfDay': 9 },
NumericLessThanEquals: { 'context.attributes.timeOfDay': 17 }
}
}]
});
`
`typescript
app.get('/mixed-access', async (req, res) => {
// Check without throwing
const canRead = await req.autorix.can('document:read', { type: 'document', id: '123' });
const canEdit = await req.autorix.can('document:edit', { type: 'document', id: '123' });
res.json({
document: canRead ? await loadDocument('123') : null,
editable: canEdit
});
});
app.post('/critical-action', async (req, res) => {
// Enforce (throws on deny)
await req.autorix.enforce('admin:critical:execute');
// This code only runs if authorized
await performCriticalAction();
res.json({ success: true });
});
`
`typescript
app.use(autorixExpress({
enforcer: autorix,
getPrincipal: (req) => req.user,
getTenant: (req) => {
// Extract from subdomain
const subdomain = req.subdomains[0];
return subdomain || req.user?.tenantId;
}
}));
// Each tenant has isolated policies
await provider.attachPolicy({
scope: { type: 'TENANT', id: 'acme-corp' },
policyId: 'acme-admins',
principals: [{ type: 'USER', id: 'alice' }]
});
await provider.attachPolicy({
scope: { type: 'TENANT', id: 'other-corp' },
policyId: 'other-admins',
principals: [{ type: 'USER', id: 'bob' }]
});
`
`typescript`
app.use(autorixExpress({
enforcer: autorix,
getPrincipal: (req) => req.user,
onDecision: (decision, req) => {
// Log all authorization decisions
logger.info('Authorization decision', {
userId: req.user?.id,
action: decision.action,
allowed: decision.allowed,
reason: decision.reason,
path: req.path,
method: req.method,
timestamp: new Date()
});
}
}));
---
@autorix/express provides an official error handler middleware to ensure authorization errors401
are returned as clean HTTP responses (, 403) instead of unhandled stack traces.
`ts
import { autorixErrorHandler } from '@autorix/express';
// Register at the end (after routes)
app.use(autorixErrorHandler());
`
This middleware automatically handles all AutorixHttpError instances and formats them as JSON responses.
Always register this middleware after all routes.
---
If you want full control over the error response format or logging, you can implement
your own handler using the exported error classes.
`ts
import { AutorixHttpError } from '@autorix/express';
app.use((err, req, res, next) => {
if (err instanceof AutorixHttpError) {
return res.status(err.statusCode).json({
error: {
code: err.code,
message: err.message
}
});
}
next(err);
});
`
---
* If no error handler is registered, Express will print authorization errors as stack traces.
* Using autorixErrorHandler() is strongly recommended to avoid this behavior.requireAuth: true
* For protected routes, use in authorize() to return a clean 401 Unauthenticated
response when no principal is present.
---
Express does not support automatic global error handling inside normal middleware.
For this reason, error handlers must be registered explicitly at the application level.
This design follows the same pattern used by mature Express libraries
(e.g. passport, express-rate-limit, celebrate`).
---
- @autorix/core - Core policy evaluation engine
- @autorix/storage - Policy storage providers
- @autorix/nestjs - NestJS integration
MIT © Chechooxd
Contributions are welcome! Please check the main repository for guidelines.
For more information, visit the Autorix documentation.