fastify-xconfig
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
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
professional | boolean | false | No | Suppress route listing on startup when true |
fancyErrors | boolean | true | No | Enable formatted error responses with status codes |
prisma | object | {} | No | Prisma integration config (see below) |
bugsnag | object | {} | No | Bugsnag error tracking config (see below) |
cors | object | {} | No | CORS config forwarded to @fastify/cors |
rateLimit | object | {} | No | Rate limiting config forwarded to @fastify/rate-limit |
multipart | object | {} | No | Multipart config forwarded to @fastify/multipart |
underPressure | object | {} | No | Back-pressure config forwarded to @fastify/under-pressure |
All middleware options accept active: false to disable that middleware entirely.
prisma Options
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
active | boolean | true | No | Enable or disable Prisma integration |
client | PrismaClient | — | Yes (if active) | Your generated PrismaClient class |
...rest | object | — | No | Passed directly to new PrismaClient(...) |
bugsnag Options
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
active | boolean | true | No | Enable or disable Bugsnag integration |
apiKey | string | — | Yes (if active) | Bugsnag project API key |
cors Options
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
active | boolean | true | No | Enable or disable CORS |
origin | string|string[] | CORS_ORIGIN env or * | No | Allowed origins |
credentials | boolean | true | No | Allow credentials |
methods | string[] | ["GET","POST","PUT","DELETE","OPTIONS"] | No | Allowed HTTP methods |
Methods
Utility decorators added to the Fastify instance:
- xEcho() — Returns
"Hello from X Enterprises!" - xSlugify(string) — Converts a string to a URL-safe slug
- xRandomUUID() — Generates a UUID v4 string;
xGenerateUUIDis an alias - xFormatBytes(bytes, decimals?) — Formats a byte count to a human-readable string
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
| Error | Cause |
|---|---|
[xConfig] professional must be a boolean | professional option is not a boolean |
[xConfig] fancyErrors must be a boolean | fancyErrors option is not a boolean |
[xConfig] prisma.client is required | Prisma is active but client was not provided |
[xConfig] prisma.client must be a PrismaClient constructor | prisma.client is not a function or class |
[xConfig] bugsnag.apiKey is required and must be a string | Bugsnag is active but apiKey is missing or not a string |
Environment Variables
| Variable | Required | Description |
|---|---|---|
NODE_ENV | No | production disables error stack traces and enables secure CORS defaults |
CORS_ORIGIN | No | Comma-separated allowed origins for production CORS |
RATE_LIMIT_MAX | No | Max requests per window (default: 100) |
RATE_LIMIT_TIME_WINDOW | No | Rate limit time window (default: "1 minute") |
BUGSNAG_API_KEY | If bugsnag active | Bugsnag project API key |
DATABASE_URL | If prisma active | Prisma 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
