Fastify Adapter
@guardcore/fastify provides a Fastify plugin that wraps the core security engine using onRequest and onSend hooks.
Installation
Section titled “Installation”pnpm add @guardcore/fastifyguardPlugin
Section titled “guardPlugin”An async Fastify plugin that registers security hooks. Initializes eagerly at registration time.
import { guardPlugin } from '@guardcore/fastify';
await app.register(guardPlugin, { config: { /* SecurityConfig */ },});Options:
| Field | Type | Required | Description |
|---|---|---|---|
config | SecurityConfig | Yes | Security configuration |
agentHandler | AgentHandlerProtocol | No | Telemetry agent |
geoIpHandler | GeoIPHandler | No | GeoIP handler for country filtering |
guardDecorator | SecurityDecorator | No | Decorator instance for per-route config |
configureCors(fastify, config)
Section titled “configureCors(fastify, config)”Configures CORS using @fastify/cors (must be installed separately).
import { configureCors, SecurityConfigSchema } from '@guardcore/fastify';
const config = SecurityConfigSchema.parse({ enableCors: true, corsAllowOrigins: ['https://app.example.com'],});
await configureCors(app, config);Hook Architecture
Section titled “Hook Architecture”The plugin registers two Fastify hooks:
onRequest Hook
Section titled “onRequest Hook”Runs before route handlers. Performs the full security pipeline:
- Creates a
FastifyGuardRequestfrom the Fastify request - Checks passthrough conditions (excluded paths)
- Resolves route configuration from decorators
- Checks security bypass conditions
- Executes the 17-check security pipeline
- Processes behavioral usage rules
- Stores guard state on the request for the
onSendhook
onSend Hook
Section titled “onSend Hook”Runs after route handlers, before the response is sent:
- Retrieves guard state from the request
- Captures the response as a
GuardResponse - Processes response through the error response factory (applies security headers, collects metrics)
- Runs behavioral return rules if configured
Full Example
Section titled “Full Example”import Fastify from 'fastify';import { guardPlugin, configureCors, SecurityDecorator, SecurityConfigSchema,} from '@guardcore/fastify';
const app = Fastify({ logger: true });
const config = SecurityConfigSchema.parse({ enableRedis: true, redisUrl: 'redis://localhost:6379', rateLimit: 100, rateLimitWindow: 60, enablePenetrationDetection: true, enableCors: true, corsAllowOrigins: ['https://app.example.com'], blockedUserAgents: ['sqlmap', 'nikto'], excludePaths: ['/health'],});
const guard = new SecurityDecorator(config);
await configureCors(app, config);await app.register(guardPlugin, { config, guardDecorator: guard,});
app.get('/health', async () => ({ status: 'ok' }));
const searchHandler = guard.rateLimit(20, 60)(async (request, reply) => { return { results: [] };});
app.get('/api/search', searchHandler);
await app.listen({ port: 3000 });Body Handling
Section titled “Body Handling”Fastify parses request bodies automatically. The FastifyGuardRequest adapter handles body conversion:
Bufferbodies are converted toUint8Arraystringbodies are encoded viaTextEncoder- Object bodies (parsed JSON) are re-serialized via
JSON.stringifythen encoded - Missing bodies return an empty
Uint8Array