X Enterprises
fastify-xauth-nile

withContext(request, fn)

Runs a callback with the Nile SDK inside a request-scoped context (headers + tenant id).

withContext(request, fn)

Runs fn(nile) inside a request-scoped Nile SDK context. The context carries the request's headers (session cookie) and the resolved tenant id (URL param > tenantHeader > nile.tenant-id cookie > optional config.tenantId), so SDK calls — including tenant-aware nile.query(...) / nile.db.query(...) — execute with the correct user and tenant.

Every call sets useLastContext: false so a previous request cannot leak tenant or cookies. Do not pass tenantId or userId into the Nile() constructor.

Signature

instance.withContext<T>(
  request: FastifyRequest,
  fn: (nile: Server) => Promise<T>
): Promise<T>

Params

NameTypeRequiredDescription
requestFastifyRequestYesThe incoming Fastify request
fn(nile: Server) => Promise<T>YesCallback receiving the context-bound Nile SDK instance

Returns

Promise<T> — whatever fn returns.

Throws

Propagates errors thrown by fn or the Nile SDK.

Examples

Tenant-aware database query

const auth = fastify.xAuthNile.get("api");

fastify.get("/api/todos", {
  preHandler: [auth.requireAuth(), auth.requireTenant()],
}, async (request) => {
  return auth.withContext(request, async (nile) => {
    const res = await nile.query("select * from todos order by created_at desc");
    return res.rows;
  });
});

Calling the Nile API as the current user

fastify.get("/api/tenants", {
  preHandler: auth.requireAuth(),
}, async (request) =>
  auth.withContext(request, async (nile) => nile.tenants.list())
);

See also

AI Context

package: "@xenterprises/fastify-xauth-nile"
method: fastify.xAuthNile.get(name).withContext(request, fn)
use-when: run Nile SDK calls (auth, users, tenants, tenant-aware db.query) with the request's session cookie and tenant id applied via AsyncLocalStorage context
usage: await fastify.xAuthNile.default.withContext(request, async (nile) => nile.db.query('select 1'))
Copyright © 2026