
@apitraffic/sails is ApiTraffic for Sails, as an installable hook. Install it and every request your application serves is recorded - request and response, headers, bodies, timing, the route Sails matched, and the outbound HTTP calls made while serving it - and checked by the ApiTraffic firewall. Sails loads installable hooks from your dependencies when it lifts, so there is no code to add.
It is @apitraffic/node, the one-install SDK, wired into Sails. It contains no capture, firewall or instrumentation logic of its own: Sails serves HTTP through Express, so requests are recorded by @apitraffic/express and checked by @apitraffic/waf, exactly as in a plain Express application. What actually runs - the firewall, redaction, exclusions, span capture - is switched on from your ApiTraffic account, not in code.
Contents
Which package should I use?
On Sails, use this package. It is @apitraffic/node placed where Sails needs it: capture first in Sails' HTTP middleware order, and the firewall right after the body parser. If you already mount @apitraffic/express yourself as an apitraffic middleware in config/http.js, see ApiTraffic already in config/http.js.
For other frameworks, see the "Which package should I install?" table in the @apitraffic/node README.
Requirements
- Node.js 20 or later.
- Sails 1.x (an optional peer dependency), with the
http hook enabled.
- The package listed in your app's own
package.json dependencies, installed in the app's own node_modules: Sails ignores hooks that are not.
- Outbound HTTPS from your servers to
ingest.apitraffic.io (telemetry) and api.apitraffic.io (settings and live configuration). Live configuration changes (redaction rules, exclusions, firewall policy) are pushed over a realtime connection to Ably, so also allow its realtime hosts; if that connection is blocked, live updates wait for a restart and nothing else is affected.
- An ingest token and a bucket ID from your ApiTraffic account. See API tokens.
Installation
npm install @apitraffic/sails
pnpm add @apitraffic/sails
yarn add @apitraffic/sails
Each adds the package to your package.json dependencies, which is what Sails loads hooks from. @apitraffic/node comes with it as a dependency.
Quick start
Set your credentials in the environment and lift as usual:
export API_TRAFFIC_TOKEN=your-ingest-token
export API_TRAFFIC_BUCKET=your-bucket-id
node app.js
That is the whole setup. To configure the hook in code instead, add config/apitraffic.js:
module.exports.apitraffic = {
token: process.env.API_TRAFFIC_TOKEN,
bucket: process.env.API_TRAFFIC_BUCKET,
};
Like any Sails config, it can be set per environment (config/env/production.js) or in config/local.js.
Where it mounts
Sails builds its Express stack from sails.config.http.middleware.order. Before that stack is built, the hook adds two entries to it:
apitraffic (capture) at the front, ahead of the cookie parser, the session, the body parser and the router, so a request a policy rejects, or that no route matches, is recorded like any other, and the request context is there in all of them.
apitrafficFirewall right after bodyParser, so body rules see the parsed body, still ahead of policies and actions. Without a bodyParser it goes just ahead of router.
Placing it yourself
An apitraffic or apitrafficFirewall entry you list in order yourself stays where you put it - for middleware that must run first, such as a health check you do not want recorded:
module.exports.http = {
middleware: {
order: [
'healthCheck',
'apitraffic',
'cookieParser',
'session',
'bodyParser',
'apitrafficFirewall',
'compress',
'poweredBy',
'router',
'www',
'favicon',
],
healthCheck: (req, res, next) => (req.path === '/health' ? res.status(200).send('ok') : next()),
},
};
ApiTraffic already in config/http.js
An application that already defines its own apitraffic middleware function in config/http.js (@apitraffic/express's middleware(), say) keeps it after installing this package: the hook sees that apitraffic is the application's own, logs that it does not set ApiTraffic up, and leaves it alone, along with any apitrafficFirewall entry, which then does nothing. To switch to the hook, delete the apitraffic function from config/http.js and move its options to config/apitraffic.js; the entries in order can stay where they are.
Configuration
Options go in sails.config.apitraffic (config/apitraffic.js), or are set as environment variables. You can mix the two.
Precedence: an option in sails.config.apitraffic wins over its environment variable, which wins over the built-in default. With no config/apitraffic.js at all, the hook reads everything from the environment. On top of that, settings from your ApiTraffic account - redaction rules, exclusions, the firewall policy, APM capture switches - are loaded at startup and pushed to every connected server in real time, without a restart or a deploy.
Sails' own config overrides work too (sails_apitraffic__waf=false in the environment, --apitraffic.waf=false on the command line). They arrive as strings, so the hook reads 'true' and 'false' as booleans for waf and debug.
To turn the hook off, set module.exports.apitraffic = false (in config/env/test.js, say). sails.config.hooks.apitraffic = false does too, by not loading it at all - use that only when config/http.js does not list apitraffic or apitrafficFirewall in order, because Sails will not lift with an entry nothing provides.
A few settings combine differently:
| Firewall on or off | Off if either waf: false is set or API_TRAFFIC_WAF_ENABLED is exactly false or 0, or off in any case. This variable does not use the switch parser below: FALSE, no or a value with spaces leaves the firewall on. Neither can turn on a firewall your account has not enabled. |
waf.offlineWafMode | API_TRAFFIC_OFFLINE_WAF_MODE wins over the config option, so you can change it during an incident without a deploy. Only exactly closed (lowercase) means closed: any other non-empty value, such as CLOSED, still overrides the option and fails open. |
captureStatementParams, captureRedisKeys | On if your config or environment turns it on, or the bucket's APM Capture settings do. |
captureCallSite | The bucket's APM Capture setting applies unless you set it in config or the environment. Set locally it can only turn code location on for the SDK's own spans: a local false does not override a bucket that has it on. The APM bridge reads API_TRAFFIC_CAPTURE_CALL_SITE (or its own captureCallSite option) itself, so a false there does turn it off for OpenTelemetry spans. |
captureStackDepth | The bucket's APM Capture setting applies unless you set it in config or the environment, which then wins. |
interceptOutbound | A blank value ("", null, an empty variable) turns outbound capture off. For the other switches, limits, sample rates, token, bucket and accountSid, a blank value counts as not set (apiHost and ingestHost fall back only when empty; a value of spaces is used as given). Two exceptions: passing debug at all, even as undefined, overrides API_TRAFFIC_DEBUG, and a blank projectRoot in code skips API_TRAFFIC_PROJECT_ROOT. |
Switches and numeric limits also accept strings (true/false, yes/no, on/off, 1/0; whole numbers for byte caps), so { captureSpans: process.env.CAPTURE_SPANS } works. An invalid value is reported once on the console and ignored. Apart from the Sails override strings above, strict is not parsed from strings - pass true or false - and API_TRAFFIC_DEBUG turns debug on only when it is exactly true (any case).
Options
token | API_TRAFFIC_TOKEN | string | - | Required. Ingest token from your ApiTraffic account. |
bucket | API_TRAFFIC_BUCKET | string | - | Required. ID of the bucket captured traffic is sent to. |
waf | API_TRAFFIC_WAF_ENABLED | false or object | unset | Local override for the firewall. false refuses it whatever the dashboard says; an object passes settings to @apitraffic/waf (and enabled: false in it turns the firewall off too). Normally left unset. |
debug | API_TRAFFIC_DEBUG | boolean | false | Log SDK activity to the console. |
strict | - | boolean | false | Makes the base client's setup() throw on misconfiguration (missing token or bucket) instead of logging. This package runs setup in the background and catches that error, so strict does not stop your app from booting, and the missing-token message is then printed only when API_TRAFFIC_DEBUG is set. Leave it off. |
accountSid | API_TRAFFIC_ACCOUNT_SID | string | learned from settings | Only needed by a process that mints embed tokens without serving requests. |
apiHost | API_TRAFFIC_API_HOST | string | api.apitraffic.io | Settings and configuration host. |
ingestHost | API_TRAFFIC_INGEST_HOST | string | ingest.apitraffic.io | Host captured traffic is sent to. |
interceptOutbound | API_TRAFFIC_INTERCEPT_OUTBOUND | switch | true | Capture outbound http, https and fetch calls. |
captureFetch | API_TRAFFIC_CAPTURE_FETCH | switch | true | Capture outbound global fetch (needs interceptOutbound). |
redactSensitiveKeys | API_TRAFFIC_REDACT_SENSITIVE_KEYS | switch | true | Mask credential-shaped body keys and query parameters. |
maxBodyBytes | API_TRAFFIC_MAX_BODY_BYTES | bytes | 524288 (512 KB) | Largest request or response body sent; a larger one is cut to the cap and ends with …[truncated by ApiTraffic: N bytes total]. |
maxRedactBodyBytes | API_TRAFFIC_MAX_REDACT_BODY_BYTES | bytes | 1048576 (1 MB) | Largest body the SDK redacts; a larger one becomes a placeholder first. |
maxFetchBodyLength | API_TRAFFIC_MAX_FETCH_BODY_LENGTH | bytes | 524288 (512 KB) | Largest outbound body captured. |
requestSampleRate | API_TRAFFIC_REQUEST_SAMPLE_RATE | 0–1 | 1 | Fraction of requests sent. 5xx responses are always sent. |
ingestBatch | API_TRAFFIC_INGEST_BATCH | switch | true | Batch payloads when your account and the ingest host support it. |
ingestGzip | API_TRAFFIC_INGEST_GZIP | switch | true | Compress those batches when your account asks for it. |
captureSpans | API_TRAFFIC_CAPTURE_SPANS | switch | true | Master switch for spans and per-request span rollups. |
captureStatements | API_TRAFFIC_CAPTURE_STATEMENTS | switch | true | Include normalized SQL/command text in spans. |
captureStatementParams | API_TRAFFIC_CAPTURE_STATEMENT_PARAMS | switch | false | Also keep statements as issued, with bind values (your users' data). |
captureRedisKeys | API_TRAFFIC_CAPTURE_REDIS_KEYS | switch | false | Include the concrete Redis key, unmasked. |
captureCallSite | API_TRAFFIC_CAPTURE_CALL_SITE | switch | true (bucket setting) | Record the application code location that started each span. |
captureStackDepth | API_TRAFFIC_CAPTURE_STACK_DEPTH | whole number ≥ 0 | 10 (bucket setting) | Application frames kept per span. |
projectRoot | API_TRAFFIC_PROJECT_ROOT | string | detected | Directory code locations are reported relative to. |
redisKeyPatterns | - | array of strings or RegExps | [] | Redis key patterns the automatic masking cannot infer. |
maxSpansPerRequest | API_TRAFFIC_MAX_SPANS_PER_REQUEST | count | 500 | Spans kept per request. |
spanSampleRate | API_TRAFFIC_SPAN_SAMPLE_RATE | 0–1 | 1 | Fraction of requests that keep full span detail. |
maxSpanMetaBytes | API_TRAFFIC_MAX_SPAN_META_BYTES | bytes | 2048 | Size cap on each span's metadata, after redaction. |
Delivery to ApiTraffic honours HTTPS_PROXY, HTTP_PROXY, ALL_PROXY and NO_PROXY. The configuration reference covers the long tail: firewall options, the APM preload's own options, offline definitions and server labels.
What gets captured
Every request the application serves over HTTP, including the ones an action never sees, with its final status and whatever your code tagged on the way:
- a request a policy rejects (
401, 403),
- a request your HTTP middleware answers itself,
- a request no route matches (
404),
- a request whose action throws, as the response
res.serverError() sent.
The route Sails matched is sent with each request, so 'GET /users/:id' in config/routes.js is the endpoint /users/{id}. See Endpoint handling.
- Inbound: method, URL, headers, request and response bodies, status and timing. Bodies over
maxBodyBytes (512 KB) are cut to that size and marked as truncated, and bodies over maxRedactBodyBytes (1 MB) are replaced by a placeholder.
- Outbound: calls made with
http, https and global fetch while serving a request, linked to it. See Outbound requests.
- Sampling:
requestSampleRate sends a fraction of requests; server errors are always sent.
Capture is @apitraffic/express, so what the Express page describes under "What is captured" holds here too. Socket.io requests to your actions (io.socket.get()) never pass through Sails' HTTP middleware: they are neither recorded nor checked by the firewall.
Data security
Nothing here needs a code change: it is configured in your ApiTraffic account and pushed to every connected server.
- Client-side redaction. Redaction rules are applied in your process before anything leaves it. Nothing is sent until your account's rules have loaded, and a request whose redaction cannot be completed is dropped, never sent unredacted.
- Sensitive key masking. Credential headers are always masked. With
redactSensitiveKeys (on by default), credential-shaped body keys and query parameters (password, token, secret, api_key and similar) are masked too.
- Exclusions. Exclusions stop matching requests from being sent at all.
Firewall
The ApiTraffic firewall is mounted by the hook as apitrafficFirewall, and whether it runs is decided in your ApiTraffic account: nothing is loaded until a policy is live, and a policy change reaches every server without a deploy. It runs right after bodyParser, so body rules see the parsed body, and ahead of your policies and actions, so a request it blocks never reaches your code. Blocked requests are still recorded, with the policy's status and waf.* tags. It guards HTTP requests only: Socket.io requests reach your policies and actions without passing through it.
To refuse it locally whatever the dashboard says, set waf: false or API_TRAFFIC_WAF_ENABLED=false:
module.exports.apitraffic = { waf: false };
Use the option when your change process requires that anything able to reject production traffic ships through a deploy; use the variable as an incident kill switch, which works even when ApiTraffic is unreachable. See Firewall setup.
APM
The APM bridge records database, cache, queue, GraphQL, gRPC and fetch/undici spans inside each request. OpenTelemetry instruments libraries by patching them as they are loaded, so it has to start before Sails and your database adapters do - by the time Sails loads its hooks, that moment has passed. So it needs a preload.
Install @apitraffic/apm, which brings the OpenTelemetry packages it needs:
npm install @apitraffic/apm
Then preload the bridge:
node -r @apitraffic/sails/register app.js
or call register() on the very first line of app.js, ahead of every other require:
require('@apitraffic/sails').register();
@apitraffic/sails/register is @apitraffic/node/register, re-exported so it resolves from an application that installs only this package (with pnpm, @apitraffic/node is not resolvable from your app). The preload reads its configuration from the API_TRAFFIC_* environment variables (register() also takes options) and never throws: if the OpenTelemetry packages are missing or fail to start, APM is skipped with a one-line reason and your application lifts normally.
The preload is for applications with no other tracing. If yours already configures OpenTelemetry, skip it and add ApiTrafficSpanProcessor from @apitraffic/apm to your own provider; with Datadog or New Relic loaded the preload steps aside on its own. See Set up APM.
Tagging, tracing and spans
The helpers work anywhere a request is being handled: actions, helpers, policies and HTTP middleware. Outside a request (a script, a bootstrap function, a scheduled job) they do nothing, and they never throw.
The package's export is the hook itself, with the helpers attached, so require('@apitraffic/sails') and import { tag } from '@apitraffic/sails' both work.
Tagging
tag(key: string, value: string) makes a request searchable, for example by account or user ID:
const { tag } = require('@apitraffic/sails');
module.exports = async function (req, res, proceed) {
tag('accountId', req.headers['x-account-id'] ?? 'none');
if (!req.headers['x-account-id']) return res.forbidden();
return proceed();
};
Keys are 1–64 characters (a letter first, then letters, digits, _, . or -); the prefixes redaction., apitraffic. and at. are reserved and dropped, and waf. is the firewall's own namespace (such a key is stored among the firewall's tags), so do not use it. Values are cut to 255 characters, and a request holds at most 32 tag keys. A tag that breaks a rule (or a missing value) is dropped, never thrown. See Tags.
Tracing
trace(content: string) is console.log for production: a timestamped note on the request (up to 255 characters, 250 per request; a longer message is dropped, not cut).
const { trace } = require('@apitraffic/sails');
trace('cart total exceeded the free-shipping threshold');
Spans
span(type, name, fn, meta?) runs fn, times it and records it on the request's waterfall, returning what fn returns; time() is the same function. startSpan(type, name, meta?) returns a handle to end() for work that does not fit one function, and addSpan() records a span you built yourself.
const { span, trace } = require('@apitraffic/sails');
module.exports = async function find(req, res) {
trace(`Loading user ${req.param('id')}`);
const user = await span('db.query', 'load user', () => User.findOne({ id: req.param('id') }));
return res.json(user);
};
type is one of db.query, redis, cache, http.out, queue, rpc, graphql or custom. getContext() and getRequestManager() expose the current request's context for advanced use; most applications never need them. See Per-request APIs.
Embed tokens
The embeddable request log (and embedded reports and dashboards) authenticate with a short-lived JWT that locks in the bucket, the filters and the request detail tabs the embed may show. It is minted on your server with an Administrator API token with no access scopes, set as API_TRAFFIC_EMBED_TOKEN (the ingest token the SDK reports with cannot mint embed tokens), and this package mints it:
const { embedToken } = require('@apitraffic/sails');
module.exports = async function token(req, res) {
const { token, expiresAt } = await embedToken({
filters: { tags: { customerId: String(req.me.id) } },
ttl: 900,
});
return res.json({ token, expiresAt });
};
The host, bucket and account come from the SDK you already configured and the token from API_TRAFFIC_EMBED_TOKEN, so a call names only what is specific to this embed. Everything is optional, except reportSid or dashboardSid for a report or dashboard embed:
bucketSid | The bucket the SDK reports to (request log only) | The bucket the embed is scoped to. A report or dashboard keeps its own scope unless you pass one. |
view | 'request-log' | 'request-log', 'report' (with reportSid) or 'dashboard' (with dashboardSid). |
filters | {} | environmentSid, criteria, streamViewSid, tags (request log) or filter, environmentSid, tags (report and dashboard) - signed into the token, so the browser cannot widen them. tags ({ customerId: id }) is written into the criteria (for a report or dashboard, the filter) safely; if you build criteria yourself, put values in double quotes through escapeCriteriaValue(). |
timeRange / timeRanges | The report's own / all | Report and dashboard embeds: the range the embed opens with ({ relative: 'last_7d' }) and the ranges the viewer may pick. |
ttl | 3600 | Token lifetime in seconds (60–86400). |
theme | 'light' | 'light', 'dark' or 'auto'. |
tabs | The API's default set | Request detail tabs this embed may show. Request log only: the API refuses it for a report or dashboard. |
features | {} | copyRequest, includeBodies. Request log only: the API refuses it for a report or dashboard. |
accountSid | From your SDK settings | Only needed in a process that does not serve requests through ApiTraffic. Also read from API_TRAFFIC_ACCOUNT_SID. |
token / apiHost | API_TRAFFIC_EMBED_TOKEN / the SDK's host | Override the credential or host for one call. |
Data behind a tab you do not grant is never returned to the browser - the tabs are an access boundary, not a display setting.
This is the one call in the package that rejects rather than going quiet. A token has a single useful outcome, and it is produced inside your own await, where a failure is a 500 on that route instead of a broken embed with nothing to explain it.
API_TRAFFIC_EMBED_TOKEN is a read credential. An Administrator API token can mint embed tokens for any bucket in its account, with any filters or none, so whoever holds it can read all of the account's captured traffic. Keep it in a secret store (never in client-side code, images or a repository), set it only on servers that mint embed tokens, and rotate it immediately if it may have been exposed.
Lifecycle: shutdown, flush and stats
sails.lower(), which Sails also runs on Ctrl-C and SIGTERM, delivers what was captured before Sails closes the HTTP server - in beforeShutdown, after your own beforeShutdown has called back - and releases the SDK's timers, realtime connection and outbound hooks once the server has closed and the last application using the hook has lowered.
On a signal Sails exits the moment its server has closed, so a request still being served when lowering began is recorded only if the process stays up long enough to deliver it. To let those finish first, stop sending traffic to the instance (drain it at the load balancer) before you signal it.
@apitraffic/node's lifecycle functions are re-exported for the cases Sails' own lifecycle does not cover:
flush({ timeoutMs }) delivers what has been captured without stopping (default timeout 2 s). Anything not delivered in time stays queued.
shutdown({ flushTimeoutMs }) stops capturing, delivers what is queued and releases everything. You do not need it when Sails lowers normally.
stats() returns delivery counters (pending, queued, delivered, recovered, dropped, breakerOpen, …), for a health endpoint or your own monitoring.
All three never throw.
TypeScript
The package ships its own declarations, for a TypeScript Sails app. ApiTrafficOptions lists every option the SDK accepts; a value of the wrong type is a compile error, and so is a misspelled key in an object literal (unlisted keys are still passed through at runtime).
Sails loads config/*.js with CommonJS, so type-check the plain JavaScript config file with a JSDoc annotation (and // @ts-check or checkJs):
module.exports.apitraffic = { debug: process.env.NODE_ENV !== 'production' };
Exported types: ApiTrafficOptions, WafConfigureOptions, ApmOptions, RegisterResult, SpanHandle, SpanMeta, EmbedTokenOptions, EmbedTokenResult and SailsHookDefinition (what the hook function returns, typed structurally so the declarations do not depend on Sails' types).
Failure behaviour
The SDK is built so that it can never be the reason your application fails.
- The hook never throws while Sails lifts. Without the
http hook it records nothing and says so in debug; until it is set up, its order entries pass requests on.
- A missing or invalid token disables telemetry and logs a clear message. Your application still lifts.
- If ApiTraffic is unreachable, requests are served normally. A short outage is absorbed by an in-memory retry queue; a longer one sheds data rather than growing without bound. See If ApiTraffic is unreachable.
- If the realtime connection fails, you lose live configuration updates and nothing else.
- Nothing is sent before your account's client-side redaction rules have loaded.
tag() and trace() never throw into your handlers, and every helper does nothing outside a request.
Want the app to refuse to boot without credentials? Check API_TRAFFIC_TOKEN and API_TRAFFIC_BUCKET yourself before you start the server. strict: true does not do it here: setup runs in the background and its error is caught.
Troubleshooting
Start with debug logging: set API_TRAFFIC_DEBUG=true (or debug: true in config/apitraffic.js) and restart. A missing token is logged even without debug. When the hook is mounted, sails.config.http.middleware.order contains apitraffic (first, unless you placed it yourself) and apitrafficFirewall.
- No requests are recorded. Check that
@apitraffic/sails is listed in your app's package.json dependencies and installed in its own node_modules, that neither sails.config.apitraffic nor sails.config.hooks.apitraffic is false, and that API_TRAFFIC_TOKEN and API_TRAFFIC_BUCKET reach the process. If config/http.js defines its own apitraffic middleware, the hook does not set ApiTraffic up (see above).
- The hook is not loaded in a monorepo. Sails looks for installable hooks only in the app's own
node_modules. If your package manager hoists @apitraffic/sails to the workspace root, add api/hooks/apitraffic/index.js containing module.exports = require('@apitraffic/sails'); and Sails loads it from there, configured the same way.
- Nothing arrives, and the SDK cannot connect. Allow outbound HTTPS to
ingest.apitraffic.io and api.apitraffic.io. Behind a proxy, set HTTPS_PROXY.
- Bodies are missing or show a placeholder. A body larger than
maxBodyBytes (512 KB) is cut, and one larger than maxRedactBodyBytes (1 MB) is replaced by a placeholder; raise the caps if you need more. See Troubleshooting.
- Socket.io requests are missing. Requests over Sails' WebSocket transport are virtual: they reach your actions without passing through the HTTP server or its middleware, so there is nothing to record, and the firewall does not check them.
- Tags set in a script or scheduled job are missing. Tags, traces and spans belong to an HTTP request; outside one the helpers do nothing.
- "the installed @apitraffic/waf has no … firewall". A live policy is not being enforced because an older
@apitraffic/waf is installed alongside. Update it to the version @apitraffic/node depends on, or remove the duplicate.
- APM shows no spans. The preload has to run before Sails and your adapters load, and
@apitraffic/apm must be installed next to it. See Set up APM.
More symptoms and fixes are in the troubleshooting guide.
Sample application
The setup guide walks through a complete application. The ApiTraffic source (not the npm package) also includes a working Sails application in examples/basic. Its only ApiTraffic-specific file is config/apitraffic.js, with credentials from the environment.
export API_TRAFFIC_TOKEN=your-ingest-token
export API_TRAFFIC_BUCKET=your-bucket-id
npm install
npm start
It listens on port 4000: try /, /users/42 (a route parameter and a span), /outbound (an outbound call) and /admin (a request a policy rejects), then open the bucket's traffic stream in ApiTraffic.
Documentation and related packages
Contributing, changelog and license
Follow @apitraffic/sails on npm to stay updated on new releases.
Follow us on our Blog and on X.
Chat with the ApiTraffic team and other members on Discord and follow our tutorials and other videos on YouTube.



How to contribute
Here are some ways you can help improve ApiTraffic:
- Give ApiTraffic a try and share your feedback to help make ApiTraffic even better for you. Feel free to reach out to us on Discord!
- Join our Discord to connect with other members, share your experiences, and learn from one another.
- Report bugs or request features by emailing support@apitraffic.io or asking on Discord.