@autofleet/fastify-boilerplate
v2.5.29
Published
Maintainers
Keywords
Readme
Fastify Boilerplate
Fastify Boilerplate is a chunk of code that is likely to be required in any Fastify server application of Autofleet, with built-in middleware for tracing, authorization, health checks, and more.
Features
- Error Handling: Custom error handling for different types of errors.
- Authorization: Adds the
zehutplugin for authorizing via JWT user header. - Security: Adds various security headers. (
helmet) - Health Checks: Kubernetes-ready liveness (
/alive) and readiness (/ready) probes with graceful shutdown support. - Stats Endpoint: Provides server and application base data.
- Tracing: Adds HTTP request tracing.
- Request Cancellation: Provides
AbortSignalon each request for operation cancellation, if request is aborted. - SWAGGER: Optionally, adds a
/documentationendpoint for the API documentation.
Usage
To use the Fastify Boilerplate, you need to import and initialize it in your application:
import Fastify from 'fastify';
import { fastifyBoilerplatePlugin } from '@autofleet/fastify-boilerplate';
import { logger } from './logger';
import { sequelize } from './models';
import { redis } from './lib/redis';
import { rabbit } from './rabbit';
import pkgJson from '../package.json' with { type: 'json' };
const API_TAGS = [
{ name: 'Animals', description: 'Animals related end-points' },
{ name: 'Users', description: 'Users related end-points' },
];
const app = Fastify();
await app.register(fastifyBoilerplatePlugin, {
logger,
tags: API_TAGS, // Optional, when provided initializes a swagger UI
name: pkgJson.name,
version: pkgJson.version,
healthManager: {
// HealthManager options - provides /alive and /ready endpoints with graceful shutdown
clients: {
sequelize: { connection: sequelize },
redis: { connection: redis },
rabbit: { connection: rabbit },
},
},
});Health Checks & Graceful Shutdown
The boilerplate integrates with @autofleet/nitur's HealthManager to provide Kubernetes-ready health endpoints and graceful shutdown capabilities.
Endpoints
/alive- Liveness probe endpoint. Returns 200 when the application is running and dependencies are healthy./ready- Readiness probe endpoint. Returns 200 when the application is ready to receive traffic, 503 during shutdown or when dependencies are unhealthy.
Features
- Automatic Health Checks: Monitors configured clients (database, cache, message queues) and reports their health status.
- Graceful Shutdown: Automatically handles SIGTERM/SIGINT signals:
- Marks the pod as not ready (failing readiness probes)
- Waits for load balancers to stop routing traffic (configurable delay)
- Closes client connections gracefully
- Shuts down the HTTP server
- Server Auto-Attachment: The HTTP server is automatically attached to HealthManager after
listen()is called.
For more details on HealthManager configuration, see the @autofleet/nitur documentation.
Request Cancellation
The boilerplate automatically provides an AbortSignal on each request through req.signal. This signal is automatically aborted when the client disconnects or the request encounters an error, allowing you to cancel ongoing operations gracefully.
Usage Example
app.route({
method: 'GET',
url: '/long-running-task',
handler: async (req, reply) => {
const { signal } = req;
try {
// Use the signal with fetch or other abortable operations
const response = await fetch('https://api.example.com/data', { signal });
const data = await response.json();
// Or check the signal manually during long operations
for (let i = 0; i < 1000; i++) {
if (signal.aborted) {
throw new Error('Operation was cancelled');
}
// Perform work...
}
return { data };
} catch (error) {
if (signal.aborted) {
reply.code(499); // Client Closed Request
return { error: 'Request cancelled' };
}
throw error;
}
}
});Best Practices
- Always check
signal.abortedbefore performing expensive operations - Use the signal with fetch requests, DB queries and other abortable APIs
- Handle cancellation gracefully by cleaning up resources
- Consider using Node.js
addAbortListenerfor attaching listeners to the signal's abort event, as it handles them safely, and returns a disposer to cleanup the listener when no longer needed.
