fastify-xauth-jwks
getUserId
Get the authenticated user's ID from a Fastify request object.
getUserId
Get the user ID from an authenticated Fastify request. Reads request.auth.userId first, then falls back to request.user.sub. Returns null if neither is present.
Signature
import { getUserId } from "@xenterprises/fastify-xauth-jwks/utils";
getUserId(request: FastifyRequest): string | null
Params
| Name | Type | Required | Description |
|---|---|---|---|
request | FastifyRequest | Yes | Authenticated Fastify request. Must have request.auth.userId or request.user.sub set by the plugin. |
Returns
string | null — The user ID (JWT sub claim), or null if the request is unauthenticated.
Throws
Does not throw.
Examples
Basic — get user ID in a route handler
import { getUserId } from "@xenterprises/fastify-xauth-jwks/utils";
fastify.get("/admin/profile", async (request) => {
const userId = getUserId(request);
const profile = await db.users.findById(userId);
return profile;
});
Realistic — use in a shared audit log helper
import { getUserId } from "@xenterprises/fastify-xauth-jwks/utils";
async function auditLog(request, action, resourceId) {
const actorId = getUserId(request);
await db.auditLogs.create({
actor: actorId,
action,
resource: resourceId,
ip: request.ip,
timestamp: new Date(),
});
}
fastify.delete("/admin/users/:id", async (request) => {
await db.users.delete(request.params.id);
await auditLog(request, "user.delete", request.params.id);
return { deleted: true };
});
See Also
- getAuthEndpoint — Get the name of the path that authenticated this request
- extractToken — Extract the raw Bearer token from the request
AI Context
package: "@xenterprises/fastify-xauth-jwks"
import: getUserId from "@xenterprises/fastify-xauth-jwks/utils"
use-when: Get the authenticated user's ID from request.auth.userId or request.user.sub
returns: string | undefined
