Connect a Strapi app
Add the @apitraffic/strapi plugin to a Strapi 5 app: install, register the middleware, configure credentials, the firewall and APM, verify and troubleshoot.
The ApiTraffic plugin for Strapi captures every request your Strapi app serves and the calls Strapi makes to other APIs, runs the ApiTraffic firewall and adds APM spans. Strapi runs on Koa, so the plugin is @apitraffic/node’s Koa integration with Strapi’s configuration around it, and it is configured through environment variables. What the firewall and APM do is switched on from your ApiTraffic account, not in code.
Before you begin
- Strapi 5, on Node.js 20 or later.
@apitraffic/strapi0.3 or later for the firewall and APM. Earlier versions capture requests only.- An ingest token and a bucket ID. The setup page in ApiTraffic creates the token for you if you are an owner or admin; see API tokens.
- Outbound HTTPS from your servers to
ingest.apitraffic.ioandapi.apitraffic.io.
Set up the plugin
Install the plugin
npm install @apitraffic/strapi
pnpm add @apitraffic/strapi
yarn add @apitraffic/strapi
bun add @apitraffic/strapi
Add the middleware
Add plugin::apitraffic.apitraffic to the array in config/middlewares.js. Leave the middlewares Strapi ships with in place and add it after them:
module.exports = [
'strapi::logger',
'strapi::errors',
'strapi::security',
'strapi::cors',
'strapi::poweredBy',
'strapi::query',
'strapi::body',
'strapi::session',
'strapi::favicon',
'strapi::public',
'plugin::apitraffic.apitraffic'
];
Installing the plugin is not enough on its own: without this entry, nothing is captured.
Set your credentials
Add your token and bucket ID to Strapi’s .env file, or set them wherever you set your other environment variables. Strapi loads .env itself.
API_TRAFFIC_TOKEN=your-ingest-token
API_TRAFFIC_BUCKET=your-bucket-id
Restart Strapi and make a request
Restart Strapi so it reads the variables, then call any endpoint, for example GET /api/articles. The setup page in ApiTraffic shows SDK connected - waiting for a request once the plugin connects and Traffic is flowing when the request arrives.
Configure the plugin
The plugin reads API_TRAFFIC_TOKEN and API_TRAFFIC_BUCKET by default. Every other API_TRAFFIC_* variable from SDK configuration applies as well, for example API_TRAFFIC_DEBUG=true or API_TRAFFIC_INTERCEPT_OUTBOUND=false.
To set options in code instead, add them to the plugin’s configuration in config/plugins.js. Any option from the SDK configuration reference can go here:
module.exports = ({ env }) => ({
apitraffic: {
config: {
token: env('API_TRAFFIC_TOKEN'),
bucket: env('API_TRAFFIC_BUCKET'),
debug: env.bool('API_TRAFFIC_DEBUG', false)
}
}
});
waf: false (or API_TRAFFIC_WAF_ENABLED=false) refuses the firewall locally; see Firewall. waf and debug also accept the words API_TRAFFIC_WAF_ENABLED does (false, 0, off, true, 1, on), so a value read with env() rather than env.bool() works as expected.
If the token or bucket is missing, Strapi logs [apitraffic] token (API_TRAFFIC_TOKEN) … not set; request capture is disabled. at startup and the middleware passes requests through untouched. It never stops Strapi from starting or serving.
What is captured
- Every request that reaches the middleware, including ones whose controller throws (reported with the status Strapi’s error handling sends) and ones the client abandons (reported as
499). - The request body as Strapi parsed it, and the response body as your controller set it - not a compressed form of it. Streamed responses such as file downloads are recorded as a placeholder.
- The route Strapi matched, with its
/apiprefix, soGET /api/articles/42is grouped as/api/articles/{id}. - Outbound calls your Strapi code makes with
http,httpsorfetch. See Outbound requests. - Requests the firewall blocks, with the policy’s status and tagged
waf.*. - Each request once, even if the middleware is listed twice.
Tags, traces and spans
The plugin exposes @apitraffic/node’s request helpers through its sdk service. Use them in controllers, services and policies:
const { factories } = require('@strapi/strapi');
module.exports = factories.createCoreController('api::article.article', ({ strapi }) => ({
async find(ctx) {
const apitraffic = strapi.plugin('apitraffic').service('sdk');
apitraffic.tag('tenant', String(ctx.state.user?.tenantId ?? 'public'));
return apitraffic.span('db.query', 'load articles', () => super.find(ctx));
}
}));
The service also offers trace, time, startSpan, addSpan, getContext, getRequestManager, stats, embedToken, escapeCriteriaValue, flush, shutdown and register. embedToken() mints with an Administrator API token set as API_TRAFFIC_EMBED_TOKEN, not the ingest token; see Embed tokens. Tags follow the tag rules; see Per-request APIs.
Firewall
The ApiTraffic firewall is part of the plugin’s middleware, and whether it runs is decided in your ApiTraffic account: nothing is loaded until you switch a policy on, and a policy change reaches every server without a deploy. It runs right after request capture, so with the middleware listed after strapi::body (as above) body rules see the parsed body, and it runs ahead of Strapi’s router, so a request it blocks never reaches a route policy or a controller. Blocked requests are recorded with the policy’s status and tagged waf.*.
IP lists, rate limits, country lists and IP reputation use the client address Koa reports. Behind a load balancer or proxy, set proxy: { koa: true } in config/server.js so Strapi trusts it; otherwise every request has the proxy’s address.
To refuse the firewall locally whatever the dashboard says (change control, or an incident switch that does not depend on the control plane), set waf: false or API_TRAFFIC_WAF_ENABLED=false:
module.exports = ({ env }) => ({
apitraffic: {
config: {
waf: false
}
}
});
Strapi’s middlewares are global, so the firewall also checks requests to the admin panel and its APIs (/admin, /content-manager, /upload and so on). Rich-text fields saved through the Content Manager can hold HTML that cross-site scripting rules match. Start a new policy in Monitor, and if editors’ saves are flagged, add a false positive exclusion for the xss category with the path pattern ^/content-manager/ and the target body, rather than switching protection off.
See Set up the firewall for policies and rules.
Application Performance Monitoring (APM)
The APM bridge records the database, cache, queue and fetch calls made while each request is served as spans on that request. Install @apitraffic/apm, which brings the OpenTelemetry packages it needs:
npm install @apitraffic/apm
OpenTelemetry patches modules as they are loaded, so it has to start before Strapi loads its database driver: the plugin itself starts too late. Preload it in the start script of your package.json, so it runs in the Strapi process and not in npm’s:
{
"scripts": {
"start": "NODE_OPTIONS='--require @apitraffic/strapi/register' strapi start"
}
}
On Windows, use cross-env to set NODE_OPTIONS. If you start Strapi from your own script, node -r @apitraffic/strapi/register server.js does the same. Strapi’s destroy phase stops APM along with the rest of the SDK, for the rest of that process. The preload reads its options from the environment before Strapi loads .env, so set APM options such as API_TRAFFIC_CAPTURE_STATEMENTS in the real environment; the token and bucket can stay in .env.
If your app already configures OpenTelemetry, add ApiTrafficSpanProcessor from @apitraffic/apm to that provider instead; see Set up APM.
Shut down
The plugin stops the SDK in Strapi’s destroy phase: it delivers what was captured, waiting up to 2 seconds, then releases the realtime connection and hooks and stops APM, so Strapi’s shutdown and strapi develop restarts are not held up. You do not need to call shutdown() yourself. Use strapi.plugin('apitraffic').service('sdk').flush() to deliver captured requests before a process is frozen or recycled.
Troubleshooting
Nothing is captured after installing the plugin
- Check that
plugin::apitraffic.apitrafficis inconfig/middlewares.js. - Look for
[apitraffic] … not set; request capture is disabled.in the Strapi log: the token or bucket did not reach the process. - Restart Strapi after changing
.envor the configuration files.
The log says the token was rejected
ApiTraffic: token rejected (HTTP 401) or (HTTP 403) means the token is invalid or cannot access the bucket in API_TRAFFIC_BUCKET. Check both values; a token belongs to one environment. See API tokens.
Routes are grouped by raw path
Update the plugin to the latest version: older builds send the raw path.
Requests are not blocked
- Check that a policy is enabled for this bucket and environment, in Enforcing mode; see Set up the firewall.
- Check that neither
waf: falsenorAPI_TRAFFIC_WAF_ENABLED=falseis set. - A middleware listed before
plugin::apitraffic.apitrafficthat answers a request (static files, CORS preflights) answers it before the firewall sees it.
Requests have no APM spans
Check that Strapi was started with the @apitraffic/strapi/register preload and that @apitraffic/apm is installed. The preload prints why when it does not start; see When the bundled setup does not start.
Related
-
SDK configuration: Every option and environment variable the plugin accepts.
-
Set up the firewall: Create a policy and switch it to Enforcing.
-
Set up APM: See where each request’s time goes.
-
Redactions: Mask sensitive fields before they leave your server.
-
Request log: See and search the requests Strapi served.