X Enterprises
fastify-xauth-jwks

hasRole

Check if a JWT user payload contains any of the specified roles.

hasRole

Check whether a decoded JWT user payload contains at least one of the specified roles. Reads user.roles which may be a single string or an array of strings. Returns false if the user object is missing or has no roles claim.

Signature

import { hasRole } from "@xenterprises/fastify-xauth-jwks/utils";

hasRole(user: object, roles: string | string[]): boolean

Params

NameTypeRequiredDescription
userobjectYesDecoded JWT payload (e.g., request.user). Must have a roles property.
rolesstring | string[]YesRole name or array of role names. Returns true if the user has any of the specified roles.

Returns

boolean — true if the user has at least one of the specified roles, false otherwise.

Throws

Does not throw.

Examples

Basic — gate a single route

import { hasRole } from "@xenterprises/fastify-xauth-jwks/utils";

fastify.delete("/admin/posts/:id", async (request, reply) => {
  if (!hasRole(request.user, "admin")) {
    return reply.code(403).send({ error: "Admin role required" });
  }

  await db.posts.delete(request.params.id);
  return { deleted: true };
});

Realistic — check multiple allowed roles

import { hasRole } from "@xenterprises/fastify-xauth-jwks/utils";

fastify.get("/admin/reports", async (request, reply) => {
  if (!hasRole(request.user, ["admin", "analyst", "viewer"])) {
    return reply.code(403).send({ error: "Reports access denied" });
  }

  return await db.reports.getAll();
});

See Also

  • requireRole — Prebuilt preHandler hook using hasRole
  • hasPermission — Check for fine-grained permission claims instead of roles

AI Context

package: "@xenterprises/fastify-xauth-jwks"
import: hasRole from "@xenterprises/fastify-xauth-jwks/utils"
use-when: Check if a JWT payload contains any of the specified role values — for conditional logic in handlers
returns: boolean
Copyright © 2026