fastify-xauth-local
requireRole
Create a Fastify preHandler that enforces role membership from the decoded JWT payload.
requireRole
Returns a Fastify preHandler function that checks whether the authenticated user holds at least one of the allowed roles. Roles are read from the JWT scope claim by default.
Signature
const api = fastify.xauthlocal.get(name: string)
api.requireRole(
allowedRoles: string | string[],
options?: {
requestProperty?: string // default: config's requestProperty ('auth')
roleProperty?: string // default: 'scope'
}
): (request: FastifyRequest, reply: FastifyReply) => Promise<void>
Params
| Name | Type | Required | Description |
|---|---|---|---|
allowedRoles | string | string[] | Yes | Role(s) that grant access. Any match is sufficient. |
options.requestProperty | string | No | Override the request property holding decoded auth (default from config) |
options.roleProperty | string | No | JWT claim that contains the user's role(s) (default: 'scope') |
Returns
An async preHandler function. Pass it in the preHandler array of a route definition.
Throws
401 Unauthorized— if no auth object exists on the request (user not authenticated)403 Forbidden— if the user is authenticated but lacks the required role(s), with messageAccess denied. Required role(s): <roles>
Examples
Basic: single required role
const api = fastify.xauthlocal.get("api");
fastify.get(
"/api/admin",
{ preHandler: [api.requireRole("admin")] },
async (request) => ({ message: "Welcome, admin", userId: request.auth.id })
);
Advanced: multiple allowed roles and a custom claim
const api = fastify.xauthlocal.get("api");
// Allow access if user has 'admin' OR 'manager' in the 'roles' claim
fastify.delete(
"/api/users/:id",
{
preHandler: [
api.requireRole(["admin", "manager"], { roleProperty: "roles" }),
],
},
async (request) => {
await db.users.delete(request.params.id);
return { deleted: true };
}
);
See Also
- createMiddleware — build custom auth middleware for a config
- isExcluded — check whether a URL is excluded from auth
AI Context
package: "@xenterprises/fastify-xauth-local"
method: fastify.xauthlocal.get('name').requireRole(roles)
use-when: Fastify preHandler factory that enforces role membership from the decoded JWT payload — returns 403 if user lacks the role
usage: { preHandler: [auth.requireRole(['admin', 'manager'])] }
