@xenterprises/fastify-xconfig
v2.2.1
Published
Fastify configuration plugin for setting up middleware, services, and route handling.
Readme
@xenterprises/fastify-xconfig
Fastify plugin for centralized middleware orchestration, health checks, and utility decorators.
Install
npm install @xenterprises/fastify-xconfigUsage
import Fastify from 'fastify';
import xConfig from '@xenterprises/fastify-xconfig';
const fastify = Fastify({ logger: true });
await fastify.register(xConfig, {
prisma: { active: false },
bugsnag: { active: false },
cors: { origin: ['http://localhost:3000'], credentials: true },
rateLimit: { max: 100, timeWindow: '1 minute' },
multipart: { limits: { fileSize: 52428800 } },
underPressure: { maxEventLoopDelay: 1000 },
});
// Utility decorators are now available:
fastify.xSlugify('Hello World'); // "hello-world"
fastify.xRandomUUID(); // "a1b2c3d4-..."
fastify.xFormatBytes(1048576); // "1 MB"
fastify.xEcho(); // "Hello from X Enterprises!"
await fastify.listen({ port: 3000 });Options
| Name | Type | Default | Required | Description |
|------|------|---------|----------|-------------|
| professional | boolean | false | No | Disable route listing on startup |
| fancyErrors | boolean | true | No | Enable formatted error responses with status codes |
| prisma | object | {} | No | Prisma client configuration (see below) |
| bugsnag | object | {} | No | Bugsnag error tracking configuration (see below) |
| cors | object | {} | No | CORS configuration passed to @fastify/cors |
| rateLimit | object | {} | No | Rate limiting configuration passed to @fastify/rate-limit |
| multipart | object | {} | No | Multipart configuration passed to @fastify/multipart |
| underPressure | object | {} | No | Back-pressure configuration passed to @fastify/under-pressure |
prisma Options
| Name | Type | Default | Required | Description |
|------|------|---------|----------|-------------|
| active | boolean | true | No | Enable/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/disable Bugsnag integration |
| apiKey | string | — | Yes (if active) | Bugsnag project API key |
cors Options
| Name | Type | Default | Required | Description |
|------|------|---------|----------|-------------|
| active | boolean | true | No | Enable/disable CORS |
| origin | string\|array | env-based | No | Allowed origins (production reads CORS_ORIGIN env var) |
| credentials | boolean | true | No | Allow credentials |
| methods | array | ["GET","POST","PUT","DELETE","OPTIONS"] | No | Allowed HTTP methods |
| ...rest | object | — | No | Passed directly to @fastify/cors |
Middleware active Flag
All middleware options (cors, rateLimit, multipart, underPressure, bugsnag, prisma) accept active: false to disable the middleware entirely. When omitted, the middleware is enabled by default.
Decorated Properties
| Name | Type | Description |
|------|------|-------------|
| fastify.prisma | PrismaClient | Prisma client instance (only if prisma is active) |
| fastify.xEcho() | function | Returns "Hello from X Enterprises!" |
| fastify.xSlugify(str) | function | Converts string to URL-safe slug |
| fastify.xRandomUUID() | function | Generates a UUID v4 string |
| fastify.xGenerateUUID() | function | Alias for xRandomUUID |
| fastify.xFormatBytes(bytes, decimals?) | function | Formats bytes to human-readable string |
Routes
| Method | Path | Description |
|--------|------|-------------|
| GET | /health | Health check endpoint with system metrics |
Health Check Response
{
"status": "healthy",
"timestamp": "2025-01-15T12:00:00.000Z",
"uptime": 3600,
"environment": "production",
"dependencies": {
"database": "up",
"redis": "not configured"
},
"resources": {
"memory": { "rss": "50 MB", "heapTotal": "30 MB", "heapUsed": "25 MB" },
"cpu": { "loadAverage": [1.2, 0.8, 0.5], "cpus": 4 },
"disk": { "free": "100 GB", "size": "500 GB" }
},
"details": {}
}Returns 200 when healthy, 503 when degraded.
Environment Variables
| Name | Required | Description |
|------|----------|-------------|
| NODE_ENV | No | development or production (affects error stack traces, CORS defaults) |
| PORT | No | Server port (default: 3000) |
| FASTIFY_ADDRESS | No | Server bind address (default: 0.0.0.0) |
| CORS_ORIGIN | No | Comma-separated CORS origins for production |
| RATE_LIMIT_MAX | No | Max requests per window (default: 100) |
| RATE_LIMIT_TIME_WINDOW | No | Rate limit window (default: 1 minute) |
| BUGSNAG_API_KEY | If bugsnag active | Bugsnag project API key |
| DATABASE_URL | If prisma active | Database connection string |
Error Reference
| Error | When |
|-------|------|
| [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 - pass your PrismaClient class from your generated client | Prisma is active but client not provided |
| [xConfig] prisma.client must be a PrismaClient constructor | prisma.client is not a function/class |
| [xConfig] bugsnag.apiKey is required and must be a string | Bugsnag is active but apiKey missing or not a string |
Fancy Error Response Format
When fancyErrors: true (default), unhandled errors return:
{
"status": 500,
"message": "Error description",
"stack": "..."
}The stack field is only included when NODE_ENV !== "production".
How It Works
xConfig is a single Fastify plugin that orchestrates registration of multiple sub-plugins in a specific order:
- Prisma — decorates
fastify.prismawith a connected PrismaClient and registers anonClosehook to disconnect on shutdown. - Middleware — registers CORS, under-pressure monitoring, rate limiting, and multipart handling (each skippable via
active: false). - Bugsnag — optional error tracking that integrates with the fancy error handler.
- Fancy Errors — sets a custom
errorHandlerthat normalizes error responses and optionally reports to Bugsnag. - @fastify/sensible — adds
.httpErrors,.to(), and other HTTP utilities. - Utilities — registers
xEcho,xSlugify,xRandomUUID, andxFormatBytesdecorators. - Health Check — registers
GET /healthwith dependency checks (database, redis), resource monitoring (memory, CPU, disk), and environment validation. - Lifecycle — sets up route listing on startup (unless
professional: true) and a goodbye log on shutdown.
The plugin is wrapped with fastify-plugin so all decorators and routes are available in the parent scope.
License
UNLICENSED
