requireAuth()
requireAuth()
Returns a preHandler middleware function that validates the Nile session from the request's cookies and attaches request.auth (the full session) and request.user (session.user, when present) to the request. Responds with 401 Unauthorized if no valid session is found.
Signature
instance.requireAuth(): (request: FastifyRequest, reply: FastifyReply) => Promise<void>
Params
requireAuth() takes no arguments. It uses the instance's excludedPaths from registration. Directory guards (/portal, /admin) are configured with protectedPaths instead of repeating this preHandler on every route.
Returns
A preHandler function to pass to a route's preHandler option.
Throws
Sends 401 Unauthorized if:
- No session cookie is present
- The session is invalid or expired
- The Nile SDK call fails (logged as
error.messageonly)
Sends 504 Gateway Timeout if sdkTimeout is configured and nile-auth does not respond within the timeout.
Examples
Basic happy-path — protect a single route
const auth = fastify.xAuthNile.get("api");
fastify.get("/api/profile", {
preHandler: [auth.requireAuth()],
}, async (request) => {
// request.user is populated here
return { id: request.user.id, email: request.user.email };
});
Chained with tenant middleware
Use requireAuth() before requireTenant() when a route needs both a session and tenant context.
const auth = fastify.xAuthNile.get("api");
fastify.get("/api/todos", {
preHandler: [
auth.requireAuth(),
auth.requireTenant(),
],
}, async (request) => {
return { tenantId: request.tenantId };
});
See also
- Protect path surfaces —
/adminand/portaldirectory guards - requireTenant() — add tenant context after auth
- requireSuperAdmin() — allowlist after auth
- getSession(request) — resolve the session without middleware
AI Context
package: "@xenterprises/fastify-xauth-nile"
method: fastify.xAuthNile.get(name).requireAuth()
use-when: Fastify preHandler factory that enforces a Nile session — returns 401 if no valid session
usage: { preHandler: [fastify.xAuthNile.get('api').requireAuth()] }
