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

  1. Route param — request.params.tenantId
  2. HTTP header — the configured tenantHeader (looked up case-insensitively)
  3. Cookie — the nile.tenant-id cookie (TENANT_COOKIE exported by @niledatabase/server)
  4. Config fallback — configs[].tenantId (request-scoped only; never passed to Nile())

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

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

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