fastify-xauth-jwks
requireEndpoint
Fastify preHandler factory that replies 403 if the request was not authenticated by the named path.
requireEndpoint
Create a Fastify preHandler hook that restricts a route to requests authenticated by a specific named path. Returns 403 Forbidden if request.auth.path does not match the specified endpoint name.
Useful when a Fastify app protects multiple URL prefixes with different JWKS providers and you need to ensure that tokens issued by one provider cannot access routes intended for another.
Signature
import { requireEndpoint } from "@xenterprises/fastify-xauth-jwks/utils";
requireEndpoint(endpointName: string): FastifyPreHandlerHook
Params
| Name | Type | Required | Description |
|---|---|---|---|
endpointName | string | Yes | The path name (key in the paths registration object) that must have authenticated this request. |
Returns
An async Fastify preHandler hook (request, reply) => Promise<void>. Replies with 403 { error: "Forbidden", message: "Must authenticate via <endpointName> endpoint" } if the check fails.
Throws
Does not throw at call time. The returned handler does not throw — it replies with 403 instead.
Examples
Basic — lock a shared route to the portal path only
import { requireEndpoint } from "@xenterprises/fastify-xauth-jwks/utils";
fastify.get("/portal/profile", {
preHandler: requireEndpoint("portal"),
handler: async (request) => {
return db.users.getProfile(request.auth.userId);
},
});
Realistic — chain multiple guards on a sensitive endpoint
import { requireEndpoint, requireRole, requirePermission } from "@xenterprises/fastify-xauth-jwks/utils";
// This route is only for admin-path tokens with the superadmin role
fastify.delete("/admin/tenants/:id", {
preHandler: [
requireEndpoint("admin"),
requireRole("superadmin"),
requirePermission("tenants:delete"),
],
handler: async (request) => {
await db.tenants.delete(request.params.id);
return { deleted: true };
},
});
See Also
- getAuthEndpoint — Read
request.auth.pathdirectly without enforcing it - requireRole — Enforce role claims on the authenticated user
- requirePermission — Enforce permission claims on the authenticated user
AI Context
package: "@xenterprises/fastify-xauth-jwks"
import: requireEndpoint from "@xenterprises/fastify-xauth-jwks/utils"
use-when: Fastify preHandler factory that returns 403 if the request was not authenticated by the named JWKS path
usage: { preHandler: [requireEndpoint('admin')] }
