X Enterprises
fastify-xauth-better

requireOrg()

Returns a preHandler that validates org membership and populates request.organization.

requireOrg()

Returns a preHandler middleware that resolves the organization ID from the request, verifies the authenticated user is a member, and populates request.organization with the full org data plus the user's membership role. Must follow requireAuth() (or a prefix-protected scope) so that request.user is available.

Signature

instance.requireOrg(): (request: FastifyRequest, reply: FastifyReply) => Promise<void>

Params

requireOrg() takes no arguments. Organization ID resolution is configured at the instance level via the organizations option.

Organization ID resolution

When organizations.enabled is true, the org ID is resolved in this order (first match wins):

  1. URL pathorganizations.orgIdFromUrl (RegExp) is matched against request.url; the first capture group is the org ID.
  2. HTTP header — the organizations.orgIdHeader request header (default: X-Organization-Id, looked up case-insensitively).
  3. Session — the session's activeOrganizationId.
  4. Route param — falls back to request.params.orgId when none of the above match.

When organizations.enabled is false (the default), only request.params.orgId is used.

Returns

A preHandler function. Sets request.organization to:

{
  id: string
  name: string
  slug: string
  logo: string | null
  metadata: object | null
  createdAt: Date
  members: Member[]
  role: string   // the current user's membership role in this org
}

Throws

  • 401 Unauthorizedrequest.user is not set
  • 400 Bad Request — no organization ID could be resolved from the request
  • 404 Not Found — org does not exist or the user cannot access it
  • 403 Forbidden — user is not a member of the organization
  • 500 Internal Server Error — Better Auth API failure

Examples

Protect a resource that belongs to an org

const userAuth = fastify.xAuthBetter.get("user");

fastify.get("/orgs/:orgId/projects", {
  preHandler: [
    userAuth.requireAuth(),
    userAuth.requireOrg(),
  ],
}, async (request) => {
  // request.organization.id, .name, .role are all set
  return { org: request.organization.name };
});

Chain with requireOrgRole for role enforcement

fastify.put("/orgs/:orgId/settings", {
  preHandler: [
    userAuth.requireAuth(),
    userAuth.requireOrg(),
    userAuth.requireOrgRole(["owner", "admin"]),
  ],
}, async (request) => {
  return { updated: true };
});

See also

AI Context

package: "@xenterprises/fastify-xauth-better"
method: fastify.xAuthBetter.get(name).requireOrg()
use-when: Fastify preHandler factory that validates org membership and populates request.organization — must follow requireAuth()
usage: { preHandler: [auth.requireAuth(), auth.requireOrg()] }
Copyright © 2026