Fastify Setup
Source and package versions
One AIWAF repository.
Python: py/aiwaf/ · Node.js: js/ · Rust/WASM: rust/ · Java: java/.
Source and canonical README.
Versions shown describe the source checkout; package releases are independent.
Current Python/Node source targets are aiwaf 1.1.8 (Python) and
aiwaf 1.1.5 (npm), with Rust/Python 0.2.7 and
WASM 0.2.5 and Java 1.3.5. Sandbox guides retain their separately pinned builds.
The source candidate is aiwaf 1.1.5 with the declared aiwaf-wasm ^0.2.5 dependency. Publish the matching WASM companion first. The native request engine still requires explicit registration and awaits initialization; a missing native API fails startup. Legacy adapters keep their separate configuration and execution path.
Offline training now uses WASM receipts to prevent handled historical requests from extending or recreating blocks after expiry or manual removal. Models still fit on history; enforcement uses fresh requests. Preserve node_training_evidence.json in the blocklist data directory, or set AIWAF_TRAINING_STATE_DIR to a durable shared directory. Invalid timestamps are excluded. Missing WASM APIs, corrupt receipts, and storage failures make training fail visibly. A crashed trainer can leave node_training_evidence.lock; confirm it has stopped before removing that lock directory. Block and receipt writes are separate, so a crash between them can require recovery.
The current reference tests use Node 22.18.0, Express 4, Fastify 5, and NestJS 11. These are tested configurations, not a claim that every framework version is supported. Use the framework and adapter matching your application. Next.js examples require Node API request/response objects; Edge middleware is not supported by this adapter.
Legacy blocklist request checks and listing are read-only. Explicit database cleanup checks expiry in the DELETE statement; CSV cleanup reads current rows under the same cross-process lock used by blocklist writes. A crash can leave <blocklist CSV path>.lock; confirm its writer has stopped before removing that directory. Lock acquisition fails after 60 seconds. Restart all old writers when upgrading. These fixes do not make the explicit native engine's per-worker state distributed.
For source development, use the committed lockfile with npm ci, run the coverage and real native checks, and audit the complete tree with npm audit. Read dependency versions and verification and native migration.
How AIWAF works: system architecture
Protect a Fastify application, confirm the adapter runs before its handler, and decide how routes and state should be managed.
A fresh CommonJS application using Fastify 5, matching the upstream adapter tests. Use a Node.js version supported by your framework and dependency lockfile. For an existing application, confirm that its ordinary routes work before integrating AIWAF.
1. Install the adapter and dependencies
npm install fastify@^5.12.7 aiwaf
Install the framework dependencies used by your existing application. The Node middleware package is aiwaf; source code and package scripts live in the monorepo's js/ directory.
2. Register the adapter
app.cjs
const fastify = require('fastify')();
const aiwaf = require('aiwaf');
fastify.register(aiwaf.fastify, {
AIWAF_MIDDLEWARES: ['auto'],
WINDOW_SEC: 10, MAX_REQ: 20, FLOOD_REQ: 40
});
fastify.get('/', async () => ({ protected: true }));
fastify.listen({ port: 3000 });How this registration works
The plugin registers request hooks. Register it before the routes it protects; Fastify plugin encapsulation affects where hooks apply.
auto selects checks based on application signals; it is not a fixed promise that every check runs. Review the Node request lifecycle and configuration reference when choosing checks.
3. Run and verify the integration
node app.cjsOpen http://127.0.0.1:3000/ in a browser. The example handler returns {"protected": true}; existing NestJS/Adonis/Sails routes return their own handler response. This proves reachability, so also test an intended rejection on a non-exempt route before rollout.
A plain curl client can fail header checks when they are selected. Inspect the actual response and logs, route policy, and observed client address. A private client or exempt path may bypass enforcement. See the controlled allow/throttle exercise for what an enforcement test should establish.
4. Discover routes and review policy
Generate a manifest after the application's routes are registered. Express applications can call aiwaf.generateExpressManifest(app, '.aiwaf/paths.json'). Other adapters expose aiwaf.generateFrameworkManifest(framework, app, outputPath, options) with framework-specific route extraction.
For a route list stored in routes.json, use the installed CLI:
npx aiwaf manifest --framework fastify --routes routes.json --output .aiwaf/paths.json
Review the resulting manifest and repeat generation when routes change. Manifest generation complements AIWAF_MIDDLEWARES: ['auto'] and explicit AIWAF_PATH_RULES overrides.
Configuration
| Area | Important options |
|---|---|
| Middleware | AIWAF_MIDDLEWARES, AIWAF_DISABLE_MIDDLEWARES, AIWAF_PATH_RULES |
| Rate limiting | WINDOW_SEC, MAX_REQ, FLOOD_REQ, cache |
| Headers | AIWAF_HEADER_VALIDATION, AIWAF_REQUIRED_HEADERS, AIWAF_HEADER_QUALITY_MIN_SCORE |
| Methods | AIWAF_METHOD_POLICY_ENABLED, AIWAF_ALLOWED_METHODS |
| Keywords | staticKeywords, AIWAF_ENABLE_KEYWORD_LEARNING, AIWAF_DYNAMIC_TOP_N |
| Honeypot | HONEYPOT_FIELD, timing settings |
| GeoIP | AIWAF_GEO_BLOCK_ENABLED, AIWAF_GEO_BLOCK_COUNTRIES, AIWAF_GEO_ALLOW_COUNTRIES |
| Models | AIWAF_MODEL_STORAGE, AIWAF_MODEL_PATH, AIWAF_MODEL_CACHE_KEY |
| Logging | AIWAF_MIDDLEWARE_LOGGING, AIWAF_MIDDLEWARE_LOG_PATH, DB/CSV options |
| WASM | AIWAF_WASM_VALIDATION, AIWAF_WASM_VALIDATE_RECENT |
AIWAF loads aiwaf-wasm when available and falls back to the JavaScript implementation when WASM initialization or conversion is not worthwhile. Small, object-heavy operations can be faster in JavaScript because crossing the JS/WASM boundary and serializing objects has a fixed cost. WASM is most useful for sufficiently large feature batches and model scoring workloads.
Operate the installed package
npx aiwaf --help
npx aiwaf status
npx aiwaf list blocklist
npx aiwaf model info
For offline training from a source checkout:
cd aiwaf/js
AIWAF_ACCESS_LOG=/path/to/access.log npm run train
PowerShell users can set $env:AIWAF_ACCESS_LOG = '/path/to/access.log' before npm run train. Application installs do not inherit the package's npm scripts; use the installed CLI or the source checkout as appropriate.
Verify and deploy
Test normal routes, narrowly scoped exemptions, configured header policy, and rate-limit behavior in staging. Persist logs and model artifacts and schedule training after traffic volume thresholds are met. In-memory enforcement is process-local; use Redis or another shared cache when rate limits must span workers.
Select the native WASM engine
Native mode: Node source candidate aiwaf 1.1.5 declares aiwaf-wasm ^0.2.5. Explicit native registration validates NativeRequestPipeline at startup; missing or incompatible support is an error. There is no JavaScript policy fallback for this engine. Installing the dependency does not switch an existing legacy middleware chain.
Select this adapter with { AIWAF_NATIVE_PIPELINE: { dataDir: "aiwaf_native_data", profile: { min_form_time: 1.0 } } }. This is a separate lowercase profile: do not mix legacy constructor options, PATH_RULES, cache or custom stores. Fastify/Hapi await startup during registration. Koa/Adonis/Next wrappers expose .ready and Nest exposes static .ready; await it before serving, and close the resolved native handle after responses complete. Bounded framework body parsing must precede parsed-body checks.
Read the native lifecycle, configuration, deployment and measurements, and migration.
