X Enterprises

fastify-xconfig

Fastify plugin that orchestrates CORS, rate limiting, multipart, health check, Prisma, and utility decorators in a single registration.

fastify-xconfig

Opinionated Fastify plugin that bootstraps a complete API server in one register call: CORS, rate limiting, multipart body parsing, back-pressure monitoring, Bugsnag error tracking, fancy error responses, a /health endpoint with system metrics, and utility decorators. Register it once at app startup before route plugins.

Installation

npm install @xenterprises/fastify-xconfig

Quick Start

import Fastify from "fastify";
import xConfig from "@xenterprises/fastify-xconfig";
import { PrismaClient } from "@prisma/client";

const fastify = Fastify({ logger: true });

await fastify.register(xConfig, {
  prisma: { client: PrismaClient },
  cors: { origin: ["http://localhost:3000"], credentials: true },
  rateLimit: { max: 100, timeWindow: "1 minute" },
  multipart: { limits: { fileSize: 52428800 } },
  fancyErrors: true,
});

fastify.xSlugify("Hello World"); // "hello-world"
fastify.xRandomUUID();           // "a1b2c3d4-..."
fastify.xFormatBytes(1048576);   // "1 MB"

await fastify.listen({ port: 3000 });

Options

NameTypeDefaultRequiredDescription
professionalbooleanfalseNoSuppress route listing on startup when true
fancyErrorsbooleantrueNoEnable formatted error responses with status codes
prismaobject{}NoPrisma integration config (see below)
bugsnagobject{}NoBugsnag error tracking config (see below)
corsobject{}NoCORS config forwarded to @fastify/cors
rateLimitobject{}NoRate limiting config forwarded to @fastify/rate-limit
multipartobject{}NoMultipart config forwarded to @fastify/multipart
underPressureobject{}NoBack-pressure config forwarded to @fastify/under-pressure

All middleware options accept active: false to disable that middleware entirely.

prisma Options

NameTypeDefaultRequiredDescription
activebooleantrueNoEnable or disable Prisma integration
clientPrismaClientYes (if active)Your generated PrismaClient class
...restobjectNoPassed directly to new PrismaClient(...)

bugsnag Options

NameTypeDefaultRequiredDescription
activebooleantrueNoEnable or disable Bugsnag integration
apiKeystringYes (if active)Bugsnag project API key

cors Options

NameTypeDefaultRequiredDescription
activebooleantrueNoEnable or disable CORS
originstring|string[]CORS_ORIGIN env or *NoAllowed origins
credentialsbooleantrueNoAllow credentials
methodsstring[]["GET","POST","PUT","DELETE","OPTIONS"]NoAllowed HTTP methods

Methods

Utility decorators added to the Fastify instance:

Routes registered by the plugin:

  • GET /health — System health check with memory, CPU, disk, and dependency metrics

fastify.prisma

When Prisma is active, fastify.prisma holds the connected PrismaClient instance. It is disconnected automatically via an onClose hook.

const user = await fastify.prisma.user.findUnique({ where: { id: userId } });

Error Reference

ErrorCause
[xConfig] professional must be a booleanprofessional option is not a boolean
[xConfig] fancyErrors must be a booleanfancyErrors option is not a boolean
[xConfig] prisma.client is requiredPrisma is active but client was not provided
[xConfig] prisma.client must be a PrismaClient constructorprisma.client is not a function or class
[xConfig] bugsnag.apiKey is required and must be a stringBugsnag is active but apiKey is missing or not a string

Environment Variables

VariableRequiredDescription
NODE_ENVNoproduction disables error stack traces and enables secure CORS defaults
CORS_ORIGINNoComma-separated allowed origins for production CORS
RATE_LIMIT_MAXNoMax requests per window (default: 100)
RATE_LIMIT_TIME_WINDOWNoRate limit time window (default: "1 minute")
BUGSNAG_API_KEYIf bugsnag activeBugsnag project API key
DATABASE_URLIf prisma activePrisma database connection string

How It Works

xConfig is a fastify-plugin-wrapped orchestrator that registers sub-plugins in dependency order: Prisma (decorates fastify.prisma + onClose disconnect), CORS/under-pressure/rate-limit/multipart middleware (each skippable via active: false), Bugsnag integration, a custom errorHandler for fancy error formatting, @fastify/sensible HTTP utilities, the four utility decorators, a GET /health route with memory/CPU/disk and database health checks, and finally a lifecycle hook that logs all registered routes on startup unless professional: true. All decorators and routes are hoisted to the parent scope via fastify-plugin.

AI Context

package: "@xenterprises/fastify-xconfig"
type: fastify-plugin
use-when: Bootstrap a Fastify app with CORS, rate limiting, multipart, Prisma, health check, and utility decorators in one registration
decorators: fastify.prisma, fastify.xEcho, fastify.xSlugify, fastify.xRandomUUID, fastify.xGenerateUUID, fastify.xFormatBytes
routes: GET /health (memory, CPU, disk, DB metrics)
env: NODE_ENV, CORS_ORIGIN, RATE_LIMIT_MAX, RATE_LIMIT_TIME_WINDOW, BUGSNAG_API_KEY, DATABASE_URL (all optional)
register-before: route plugins — xConfig must be registered first
Copyright © 2026