X Enterprises
fastify-xauth-local

createMiddleware

Create a custom auth middleware for a config with override options — useful for one-off route protection outside the automatic prefix hook.

createMiddleware

Creates a new onRequest-compatible middleware function for a config instance. All options default to the config's values but can be overridden per-call — useful for protecting individual routes outside the automatic prefix hook, or for building optional-auth variants.

Signature

const api = fastify.xauthlocal.get(name: string)

api.createMiddleware(options?: {
  excludedPaths?: Array<
    | string
    | RegExp
    | { url: string | RegExp; methods?: string[] }
  >
  requestProperty?: string   // default: config's requestProperty
  credentialsRequired?: boolean  // default: config's credentialsRequired
  getToken?: (request: FastifyRequest) => string | undefined
}): (request: FastifyRequest, reply: FastifyReply) => Promise<void>

Params

NameTypeRequiredDescription
options.excludedPathsArrayNoPaths/patterns to skip — same format as plugin excludedPaths
options.requestPropertystringNoOverride where decoded token is attached on request
options.credentialsRequiredbooleanNoOverride whether a token is mandatory
options.getTokenFunctionNoCustom (request) => token extraction function

Returns

An async function (request, reply) => Promise<void> suitable for use as an onRequest or preHandler hook.

Throws

Replies with 401 Unauthorized for missing or invalid tokens (when credentialsRequired is true).

Examples

Basic: optional auth on a public route

const api = fastify.xauthlocal.get("api");

// Attach user if a valid token is present, but don't block unauthenticated access
const optionalAuth = api.createMiddleware({ credentialsRequired: false });

fastify.get(
  "/api/posts",
  { onRequest: [optionalAuth] },
  async (request) => {
    const userId = request.auth?.id; // may be undefined
    return posts.list({ userId });
  }
);
const api = fastify.xauthlocal.get("api");

const cookieAuth = api.createMiddleware({
  getToken: (request) => request.cookies?.session_token,
  credentialsRequired: true,
});

fastify.get(
  "/api/dashboard",
  { onRequest: [cookieAuth] },
  async (request) => ({ user: request.auth })
);

See Also

  • requireRole — enforce role membership as a preHandler
  • isExcluded — check whether a URL/method is excluded for this config

AI Context

package: "@xenterprises/fastify-xauth-local"
method: fastify.xauthlocal.get('name').createMiddleware(options?)
use-when: Create a custom auth middleware with overridden options (credentialsRequired, getToken, etc.) for specific route groups
returns: Fastify preHandler function
Copyright © 2026