X Enterprises
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

NameTypeRequiredDescription
allowedRolesstring | string[]YesRole(s) that grant access. Any match is sufficient.
options.requestPropertystringNoOverride the request property holding decoded auth (default from config)
options.rolePropertystringNoJWT 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 message Access 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

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'])] }
Copyright © 2026