fastify-xauth-nile
requireTenant()
Returns a Fastify preHandler middleware that resolves and requires tenant context for a route.
requireTenant()
Returns a preHandler middleware function that resolves the Nile tenant id for the request and attaches it as request.tenantId. Responds with 400 Bad Request if no tenant id can be resolved.
Signature
instance.requireTenant(): (request: FastifyRequest, reply: FastifyReply) => Promise<void>
Params
requireTenant() takes no arguments. It uses the instance's tenantHeader from registration (default x-tenant-id).
Resolution order
- Route param —
request.params.tenantId - HTTP header — the configured
tenantHeader(looked up case-insensitively) - Cookie — the
nile.tenant-idcookie (TENANT_COOKIEexported by@niledatabase/server) - Config fallback —
configs[].tenantId(request-scoped only; never passed toNile())
Values must match ^[A-Za-z0-9_-]{1,128}$ or they are ignored.
Returns
A preHandler function to pass to a route's preHandler option.
Throws
Sends 400 Bad Request when none of the resolution sources produce a tenant id.
Sends 403 Forbidden when verifyTenant: true is configured and the session user is not a member of the resolved tenant.
Examples
Tenant-scoped route via header or cookie
const auth = fastify.xAuthNile.get("api");
fastify.get("/api/todos", {
preHandler: [auth.requireAuth(), auth.requireTenant()],
}, async (request) => {
return { tenantId: request.tenantId };
});
Tenant from the URL
fastify.get("/api/tenants/:tenantId/todos", {
preHandler: [auth.requireAuth(), auth.requireTenant()],
}, async (request) => {
// request.tenantId === request.params.tenantId
return { tenantId: request.tenantId };
});
See also
- requireAuth() — session enforcement
- Protect path surfaces —
access: "tenant"on/affiliates - withContext(request, fn) — run tenant-aware SDK calls with the resolved tenant
AI Context
package: "@xenterprises/fastify-xauth-nile"
method: fastify.xAuthNile.get(name).requireTenant()
use-when: Fastify preHandler factory that requires tenant context — resolves URL param > header > nile.tenant-id cookie; 400 if absent
usage: { preHandler: [fastify.xAuthNile.get('api').requireTenant()] }
