X Enterprises
fastify-xauth-jwks

extractToken

Extract a Bearer JWT from the Authorization header of a Fastify request.

extractToken

Extract the raw JWT string from the Authorization: Bearer <token> header of a Fastify request object. Returns null if the header is absent or does not start with Bearer .

Signature

import { extractToken } from "@xenterprises/fastify-xauth-jwks/utils";

extractToken(request: FastifyRequest): string | null

Params

NameTypeRequiredDescription
requestFastifyRequestYesFastify request object. Reads request.headers.authorization.

Returns

string | null — The raw JWT string (without the Bearer prefix), or null if no valid Bearer token is present.

Throws

Does not throw.

Examples

Basic — extract token in a custom hook

import { extractToken } from "@xenterprises/fastify-xauth-jwks/utils";

fastify.addHook("onRequest", async (request, reply) => {
  const token = extractToken(request);

  if (!token) {
    return reply.code(401).send({ error: "Missing token" });
  }

  // pass token downstream
  request.rawToken = token;
});

Realistic — use with manual verifyJWT

import { extractToken } from "@xenterprises/fastify-xauth-jwks/utils";

fastify.post("/webhooks/stripe", async (request, reply) => {
  const token = extractToken(request);
  if (!token) {
    return reply.code(401).send({ error: "Access token required" });
  }

  const payload = await fastify.xAuth.validators.portal.verifyJWT(token);
  if (!payload) {
    return reply.code(401).send({ error: "Invalid token" });
  }

  await processWebhook(request.body, payload.sub);
  return { received: true };
});

See Also

  • decodeToken — Decode the payload of an extracted token without verification
  • verifyJWT — Verify an extracted token against a path's JWKS

AI Context

package: "@xenterprises/fastify-xauth-jwks"
import: extractToken from "@xenterprises/fastify-xauth-jwks/utils"
use-when: Extract the Bearer token string from a Fastify request's Authorization header
returns: string | null
Copyright © 2026