Skip to main content

AuthzX + Express

Add authorization to your Express API in 5 minutes.

Install

npm install @authzx/sdk

Set up the client

import { AuthzX } from '@authzx/sdk'

const authzx = new AuthzX({
apiKey: process.env.AUTHZX_API_KEY,
})

Built-in middleware

The SDK includes Express middleware out of the box:

import express from 'express'

const app = express()

// Protects route — extracts user ID from X-User-ID header
app.get('/documents/:id', authzx.middleware('document', 'read'), (req, res) => {
res.json({ id: req.params.id, content: '...' })
})

app.put('/documents/:id', authzx.middleware('document', 'write'), (req, res) => {
res.json({ updated: true })
})

app.delete('/documents/:id', authzx.middleware('document', 'delete'), (req, res) => {
res.json({ deleted: true })
})

Custom subject extraction

If your user ID comes from a JWT or session:

app.get('/documents/:id',
authzx.middleware('document', 'read', (req) => req.user.id),
handler
)

Manual check

For more control, call check() directly:

app.get('/documents/:id', async (req, res) => {
const allowed = await authzx.check(
{ id: req.user.id, type: 'user', roles: req.user.roles },
'read',
{ id: req.params.id, type: 'document' }
)

if (!allowed) {
return res.status(403).json({ error: 'forbidden' })
}

res.json({ id: req.params.id, content: '...' })
})

Full response with reason

app.get('/documents/:id', async (req, res) => {
const resp = await authzx.authorize({
subject: { id: req.user.id, type: 'user' },
resource: { id: req.params.id, type: 'document' },
action: { name: 'read' },
})

if (!resp.decision) {
return res.status(403).json({
error: 'forbidden',
reason: resp.context.reason,
})
}

res.json({ id: req.params.id })
})

Using the local agent

const authzx = new AuthzX({
baseUrl: 'http://localhost:8181',
})

Same middleware, same API — just faster responses.

Error handling

import { AuthzXError } from '@authzx/sdk'

app.use((err, req, res, next) => {
if (err instanceof AuthzXError) {
if (err.isAuthError) {
return res.status(500).json({ error: 'AuthzX configuration error' })
}
}
next(err)
})