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):
- URL path —
organizations.orgIdFromUrl(RegExp) is matched againstrequest.url; the first capture group is the org ID. - HTTP header — the
organizations.orgIdHeaderrequest header (default:X-Organization-Id, looked up case-insensitively). - Session — the session's
activeOrganizationId. - Route param — falls back to
request.params.orgIdwhen 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 Unauthorized—request.useris not set400 Bad Request— no organization ID could be resolved from the request404 Not Found— org does not exist or the user cannot access it403 Forbidden— user is not a member of the organization500 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
- requireOrgRole(roles) — enforce role within the org after requireOrg()
- requireAuth() — always precede requireOrg() with auth
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()] }
