Fastify is secure by design in several places, but only if teams use its schema-first model, keep its safe defaults and understand how plugin encapsulation decides which routes are protected. Fastify is one of the most widely used Node.js web frameworks for APIs. Its security posture rests on four building blocks: JSON Schema validation and serialisation compiled per route, an encapsulated plugin tree that scopes hooks and authentication, server factory options that bound requests and payloads, and ecosystem plugins such as @fastify/rate-limit. This guide explains each block in practitioner terms and shows where real deployments go wrong.
The guide is written for API engineers, application security reviewers and platform teams who own Fastify services, including the service accounts, API keys and tokens those services accept and use. It is based on the Fastify project's public reference documentation and the @fastify/rate-limit README as of November 2026. Option defaults change between major versions, so confirm each setting against the version you run. For general Node.js runtime hardening, see the Node.js Security Guide; for the Express framework, see the Express.js Security Guide.
Key takeaways
- Fastify validates
body,querystring,paramsandheadersagainst JSON Schema per route, but only when a schema is declared. A route with no schema accepts whatever the parser produces. - Response schemas are a data leak control as well as a performance feature: fields not listed in the schema are not serialised.
- Schemas are code. Fastify compiles them with
new Function(), so never build schemas from user input. - Plugin encapsulation decides which routes inherit an authentication hook. A route registered in the wrong context is silently public.
- Keep the safe defaults:
onProtoPoisoningandonConstructorPoisoningset to'error',allowUnsafeRegexfalse, and a sensiblebodyLimit. - Set
requestTimeoutwhen Fastify is reachable without a reverse proxy, and configuretrustProxyto a specific address list, never a blankettrueon a directly reachable origin. - Rate limits from
@fastify/rate-limitare per instance unless you add a shared store, and they key on IP by default, which depends on correct proxy trust.
The Fastify security model in brief
Fastify's design shapes where security controls live. The framework documentation states that Fastify uses a schema-based approach, recommending JSON Schema to validate routes and serialise outputs, and that it compiles each schema into a fast function. Request validation relies on Ajv v8 and response serialisation on fast-json-stringify.
The second pillar is encapsulation. Fastify documents that everything except the root context is a plugin, and that the encapsulation context governs which decorators, hooks and plugins are available to which routes. Child contexts see what their ancestors registered, but a parent does not see what its children registered. Authentication, authorisation and per-route limits are usually implemented as hooks or plugins, so the shape of the plugin tree is the shape of your access control.
The third pillar is the server factory: options passed when the instance is created, such as bodyLimit, requestTimeout, trustProxy and the poisoning protections. These act on every request before your handler runs.
Seen through a non-human identity lens, a Fastify API is usually a gate for machine callers: other services presenting API keys, OAuth access tokens, mTLS client certificates or signed webhooks. The controls below decide whether those credentials are checked on every route, whether their scope is enforced, and whether a leaked or abused credential can be throttled and traced.
Schema-first validation: what it covers and what it does not
A Fastify route can declare a schema object with four validation targets. The documentation lists body for POST, PUT or PATCH bodies, querystring (or query), params for route parameters and headers. When a schema is present, invalid input is rejected with a 400 response before the handler runs. When it is absent, there is no validation at all, which is the most common gap in real code reviews.
Content types and custom parsers
The documentation is explicit that validation is only attempted when the content type is application/json, unless the body schema uses the content property to define a schema per content type. When content is used, it must enumerate every content type the handler expects. Fastify also warns that with custom content type parsers, the parsed body is validated only when the request content type exactly matches a key in the schema's content map. In practice this means a handler that accepts text/plain or a form encoding through a custom parser may receive unvalidated data if the schema only describes JSON. Review every addContentTypeParser call alongside the schemas of the routes it feeds.
Type coercion and additional properties
Ajv will try to coerce values to the types declared in the schema, both to pass validation and to hand typed data to the handler. Fastify ships a custom Ajv configuration that includes coerceTypes: 'array', and the documentation asks teams to evaluate whether that behaviour meets their requirements. Coercion is convenient for query strings, but in a JSON body it can mask client bugs or let a string such as "1" pass where a strict integer was intended. Fastify shows how to supply separate Ajv instances per validation target with options such as removeAdditional, coerceTypes and allErrors. A common NHI Mgmt Group recommendation is to disable coercion for bodies, keep it for query strings and route parameters, and set additionalProperties: false on object schemas that represent privileged fields so that a caller cannot smuggle a role or tenantId property through. This is the Fastify expression of mass assignment protection, covered in the OWASP API Security Top 10.
Schemas are code
Fastify's documentation carries a warning that schema definitions must be treated as application code because validation and serialisation use new Function(), which is unsafe with user-provided schemas. Never accept a schema from a request, a tenant configuration record or an unreviewed shared registry. Shared schemas added with addSchema and referenced through $ref should live in source control with the same review as handler code.
Async validation and denial of service
Ajv supports $async schemas, but Fastify says they should not be used for initial validation because accessing databases during validation may lead to denial of service. Database lookups, such as checking that a referenced object belongs to the caller, belong in a preHandler hook after cheap structural validation has passed. The documentation also requires custom validators to return { error } objects rather than throwing, because thrown errors combined with async preValidation hooks can cause unhandled promise rejections that crash the process. A crash on crafted input is an availability bug that a caller holding any valid credential can trigger repeatedly.
Response schemas and accidental data exposure
Serialisation is the less discussed half of schema-first design. Fastify documents that when a response schema is provided, it uses fast-json-stringify to send JSON, and that an output schema can drastically increase throughput and help prevent accidental disclosure of sensitive information. Properties not described by the schema are dropped from the response.
This matters whenever a handler returns an object straight from a database or an upstream service. Without a response schema, a newly added column such as apiKeyHash, mfaSecret, internalNotes or a service account's client secret flows to callers the moment it exists. With a response schema, the new field stays private until someone deliberately adds it. Response schemas are keyed by status code, and Fastify supports '2xx' and default keys so error and success shapes can both be constrained.
Practical rules for response schemas:
- Declare a response schema for every route that returns objects from storage, and for every error shape your error handler produces.
- Treat a response schema change that adds a field as a data classification decision, not a refactor.
- Review shared schemas used for both input and output separately. An input schema that permits
passwordmust never be reused as an output schema. - Do not echo raw validation error details from internal services. Fastify's
schemaErrorFormatterand error handler let you return consistent, minimal messages.
Plugins, encapsulation and authentication scope
The encapsulation documentation uses an example that doubles as a security lesson. A bearer authentication plugin is registered inside an authenticatedContext plugin, and the /one route registered in that context requires a token. A separate publicContext registers /two and a grandchild context registers /three; neither sees the authentication plugin, so both are reachable without credentials. That is the intended behaviour, and it is exactly how routes become accidentally public when a developer adds a route to the wrong file or wraps a plugin in an extra register call.
The same rules apply in reverse. Fastify notes that a parent context does not have access to plugins registered in its children, so a hook added deep inside a child does not protect sibling routes. Utilities such as fastify-plugin deliberately break encapsulation so a decorator or hook applies to the parent scope; that is useful for shared authentication but means a misbehaving plugin can affect every route.
Designing an authentication tree
- Register authentication once, at the highest context that should require it, and register public routes in a clearly named sibling context. Make the public set short and reviewable.
- Prefer an
onRequesthook for authentication so that unauthenticated requests are rejected before body parsing and validation consume resources. - Enforce authorisation, such as token scopes and object ownership, in
preHandlerafter validation, where typed parameters are available. - Add an automated test that lists every route with
fastify.printRoutes()or the route table and asserts which ones are expected to be unauthenticated. Fail the build on any new public route. - Keep the
allowErrorHandlerOverridedefault offalse. Fastify documents that this preventssetErrorHandlerfrom being called more than once in a scope, so a later plugin cannot silently replace an error handler that strips sensitive details.
Machine credentials
The encapsulation example hard-codes a bearer key in source to illustrate the plugin. Production services should load API keys and token verification material from a secrets manager or workload identity, compare keys in constant time, and support at least two active keys so that rotation does not cause an outage. Map each key or OAuth client to a named calling service so that logs and rate limits identify the non-human identity, not just an IP address. See the API Security Guide for the wider credential lifecycle.
Server factory options that bound abuse
Several options passed to the Fastify factory are effectively security settings. The defaults below are quoted from the server reference; check them against your major version.
| Option | Documented default | Security relevance |
|---|---|---|
bodyLimit | 1048576 bytes (1 MiB) | Maximum accepted payload. If a preParsing hook decodes the stream, the limit applies to the decoded size. Lower it on routes that only take small JSON. |
onProtoPoisoning | 'error' | Rejects JSON containing __proto__, via secure-json-parse. Do not change to 'ignore'. |
onConstructorPoisoning | 'error' | Rejects JSON containing constructor keys used in prototype poisoning. |
requestTimeout | 0 (no limit) | Fastify says it must be set to a non-zero value, for example 120 seconds, to protect against denial of service when there is no reverse proxy in front. |
connectionTimeout | 0 (no timeout) | Socket timeout; consider setting alongside requestTimeout. |
handlerTimeout | 0 (no timeout) | Application-level limit for the whole route lifecycle; returns 503 and aborts request.signal when exceeded. |
keepAliveTimeout | 72000 ms | HTTP/1 keep-alive window; align with your load balancer. |
maxParamLength | 100 | Limits captured route parameter length; Fastify notes it does not protect against ReDoS in route regexes. |
allowUnsafeRegex | false | Rejects potentially catastrophic regular expressions in routes at registration. Keep it disabled. |
requestIdHeader | false | If enabled, any caller can set the request ID; Fastify performs no validation of it. |
Two of these deserve comment. Prototype poisoning is a Node.js-specific class of bug in which attacker-controlled JSON keys alter object prototypes; Fastify's defaults reject it at parse time, and the Prototype Pollution Guide explains the wider risk. ReDoS is the reason allowUnsafeRegex exists; Fastify points out that maxParamLength is checked only after the expression has run, so the regex safety check is the real control. See the Regular Expression Denial of Service (ReDoS) Guide for schema pattern keywords, which deserve the same scrutiny.
Reverse proxies, trustProxy and client identity
The Fastify recommendations guide states that the Fastify team strongly considers exposing a Node.js application directly to the internet to be an anti-pattern, and recommends a reverse proxy for TLS termination, HTTP to HTTPS redirects, multiple domains and static files. A proxy also gives you a single place for connection limits and header normalisation.
Once a proxy is in front, the application needs to know which forwarded headers to believe. trustProxy defaults to false. It accepts true (trust all proxies), a string or array of IP addresses and CIDR ranges, or a custom function. The documentation notes that hop-count-only trust is disabled because it cannot validate the immediate peer and lets direct clients spoof X-Forwarded-* values, and warns that request.ip, ips, host and protocol must be treated as untrusted input unless the proxy chain is explicitly trusted and validated. It adds that custom trust functions must validate the address argument.
The consequences reach well beyond logging. Rate limiting, IP allow lists, audit trails and any rule that treats internal addresses as trusted all depend on request.ip. If trustProxy: true is set and the origin is also reachable directly, any caller can claim to be any address. Set trustProxy to the exact addresses of your load balancers, block direct access to the origin at the network layer, and never authorise a request on source address alone.
Rate limiting with @fastify/rate-limit
The @fastify/rate-limit plugin adds an onRequest hook that checks whether a client, identified by IP address by default, has made too many requests in the configured time window. Callers over the limit receive a 429 response with a retry-after header.
Settings that matter for security, as documented in the plugin README:
global: applies the limit to all routes within the encapsulation scope (defaulttrue). Because it follows encapsulation, registering the plugin inside a child context limits only that context.maxandtimeWindow: defaults are 1000 requests per minute. Both can be async functions, so limits can vary by calling identity or plan.keyGenerator: defaults to the normalised request IP, which uses forwarded headers only whentrustProxyis enabled. IPv6 addresses are masked to anipv6Subnetprefix, 64 by default. For authenticated machine callers, key on the client ID or service identity after authentication, usinghook: 'preHandler'.redis: the default store is in-memory, so with several instances each one counts separately. Use a shared store for consistent limits, and tune its timeouts as the README recommends.skipOnError: whentrue, requests are allowed if the store is unreachable. Decide deliberately whether your limiter fails open or closed.ban: after a number of 429 responses, return 403 instead, with anonBanReachcallback for alerting.allowList: excludes addresses or keys from limiting. Keep it short and review it, because an allow-listed key is an unthrottled credential.
The README also warns that an attacker could discover valid URLs if 404 handling is not rate limited, and shows applying fastify.rateLimit() as a preHandler on setNotFoundHandler. Apply tighter limits on authentication, token exchange and password reset routes than on read endpoints. For broader design patterns, see the Rate Limiting and API Abuse Guide and the OWASP API Top 10 API4 Unrestricted Resource Consumption Guide.
Security headers, CORS, logging and dependencies
In the Fastify model, browser security headers and CORS policy are added through ecosystem plugins, configured per encapsulation scope like any other plugin. For pure machine-to-machine APIs, browser headers matter less than strict CORS: do not enable wildcard origins with credentials, and do not register CORS at all on internal service APIs that no browser should call. For APIs that also serve browser clients, apply a security headers plugin at the root context and test the headers in CI, because a plugin registered in a child context covers only that child.
Fastify integrates the Pino logger. Log the authenticated caller identity, route, status and request ID for every request, and configure redaction for authorization headers, cookies and any body field that can hold secrets. Logs are a frequent source of leaked API keys and bearer tokens. Ship them to a central store so that a misused service credential can be traced across instances.
Finally, treat the @fastify/* plugins and their transitive dependencies as part of the attack surface. Pin versions, watch the project's security advisories, and keep Fastify on a supported major release alongside a supported Node.js version, as covered in the Node.js End of Life Versions page.
Common failure patterns
- Routes without schemas. Handlers that read
request.bodywith no declared schema, often added in a hurry or ported from another framework. - Validation skipped by content type. A custom parser feeds a handler whose schema only describes JSON, so non-JSON requests reach the handler unchecked.
- No response schema. Database rows returned directly, leaking hashes, secrets or internal flags when the table changes.
- Authentication in the wrong scope. A new route registered in a context that never received the authentication hook, or a hook added in a child context that developers assumed was global.
- User-influenced schemas. Schemas assembled from tenant configuration, which the documentation warns is unsafe because schemas compile to code.
- Blanket proxy trust.
trustProxy: trueon an origin that is reachable directly, which lets callers spoof their IP address and bypass IP-keyed rate limits. - Timeouts left at zero.
requestTimeoutunset on services exposed without a proxy. - Per-instance rate limits. In-memory limiter stores across a fleet, multiplying the effective limit by the number of replicas.
- Database calls in validation.
$asyncschemas that hit storage before cheap checks, turning invalid requests into expensive ones.
Practitioner checklist
- Declare
body,querystring,paramsandheadersschemas on every route that reads them, and fail CI on routes without a schema. - Set
additionalProperties: falseon input objects that map to stored records, and decide coercion settings per validation target. - Declare response schemas for success and error status codes on every route returning stored data.
- Keep schemas in source control and never construct them from request or tenant data.
- Register authentication at the highest required context, keep public routes in one named context, and test the route inventory.
- Keep
onProtoPoisoningandonConstructorPoisoningat'error'andallowUnsafeRegexatfalse. - Set
bodyLimit,requestTimeoutandhandlerTimeoutto values that fit each service. - Run behind a reverse proxy, set
trustProxyto explicit proxy addresses, and block direct origin access. - Use a shared store for
@fastify/rate-limit, key authenticated routes on caller identity, and rate limit the 404 handler. - Redact authorisation headers and secrets in logs, and log the calling service identity on every request.
- Load API keys and token keys from a secrets manager and support overlapping keys for rotation.
Standards and references
- Fastify: Validation and Serialization
- Fastify: Server reference (factory options)
- Fastify: Encapsulation
- Fastify: Recommendations
- @fastify/rate-limit README
- OWASP: API Security Top 10 2023
- OWASP: Application Security Verification Standard 5.0
- NIST: SP 800-53 Rev. 5 (SI-10 Information Input Validation, SC-5 Denial-of-service Protection)
Related NHI Mgmt Group resources: Express.js Security Guide · Node.js Security Guide · API Security Guide · OpenAPI Specification Security Guide