Developer guide
OFAC API in Node.js: screening and error handling
Build OFAC screening in Node.js with a complete HTTP example, explicit source selection, idempotency, safe failures, and review handoffs.
On this page
What this Node.js integration does
OFAC is the U.S. Treasury authority that publishes the SDN and non-SDN sanctions data. This tutorial calls SanctionsKit, not an OFAC-operated screening endpoint. Keep the original authority and list identity visible in each result.
The client submits a subject, validates the response, and prints only the screening ID, status, and candidate count. It does not approve a customer, resolve an identity, or make a legal decision. A nonzero exit leaves the local operation incomplete.
Prepare the runtime and a synthetic request
Use Node.js 22 or later on a trusted server or CLI. This implementation uses the built-in fetch client and Node standard-library modules, so no SDK or npm dependency is required.
Save the following as request.json. Mira Calder is an invented subject and sandbox@1 uses synthetic fixtures, not a current production sanctions search. Set SANCTIONSKIT_API_KEY to your test key in the process environment. Set SCREENING_OPERATION_ID to a new persistent identifier for this operation, and reuse it only for an unchanged retry.
{
"subject": {
"name": "Mira Calder",
"entityType": "person",
"birthDate": "1984"
},
"package": "sandbox@1",
"retention": "standard"
}Send the request and validate the result
Save the client as screen.mjs. The endpoint is fixed to SanctionsKit’s HTTPS API. The example rejects redirects, requires explicit authorization before using a live key, and does not retry automatically. Production integrations should preserve the operation state before the first network call.
// Node.js 22+. Server or trusted CLI only. No third-party packages.
import { readFileSync } from 'node:fs';
const endpoint = 'https://www.sanctionskit.com/api/v1/screenings';
const maxResponseBytes = 8 * 1024 * 1024;
async function main() {
const key = process.env.SANCTIONSKIT_API_KEY;
const operation = process.env.SCREENING_OPERATION_ID;
if (!key || !operation) throw new Error('Set the API key and a persistent operation ID.');
if (!/^sk_test_/.test(key) && !(key.startsWith('sk_live_') && process.env.ALLOW_LIVE_SCREENING === 'yes')) {
throw new Error('Use a test key, or explicitly authorize a live screening.');
}
const raw = readFileSync(process.argv[2] ?? '../request.sandbox.json');
if (raw.length > 64 * 1024) throw new Error('Request file exceeds this example’s 64 KiB limit.');
const body = JSON.parse(raw.toString('utf8'));
if (!body.subject || (!!body.sources === !!body.package)) throw new Error('Supply a subject and exactly one of sources or package.');
const response = await fetch(endpoint, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(25000),
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', 'Idempotency-Key': operation },
body: JSON.stringify(body),
});
if (!response.body) throw new Error('Incomplete response: missing body.');
const chunks = []; let bytes = 0;
for await (const chunk of response.body) {
bytes += chunk.length;
if (bytes > maxResponseBytes) throw new Error('Incomplete response: size limit exceeded.');
chunks.push(chunk);
}
const envelope = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (!response.ok) {
// Keep the raw error body and submitted identity out of routine logs.
const code = typeof envelope?.error?.code === 'string' ? envelope.error.code : 'unknown';
throw new Error(`Screening incomplete: HTTP ${response.status}, code ${code}.`);
}
const data = envelope?.data;
if (!data || typeof data.id !== 'string' || !data.id ||
!['potential_match', 'no_match'].includes(data.status) || !Array.isArray(data.matches) ||
(data.status === 'no_match' && data.matches.length !== 0) ||
(data.status === 'potential_match' && data.matches.length === 0)) {
throw new Error('Incomplete response: unexpected screening shape.');
}
console.log(JSON.stringify({ id: data.id, status: data.status, candidateCount: data.matches.length }));
}
main().catch((error) => {
// Errors never become a no_match result. No automated retry is performed.
console.error('Screening incomplete. Check the operation before retrying.');
process.exitCode = 1;
});Run the client
Run this from the directory containing request.json and the project files. Keep the API key out of committed files and shell tracing. The tutorial’s request-file limit is 64 KiB and its response parsing limit is 8 MiB; these are client safeguards, not claims about API service limits.
Use an explicit AbortSignal and reject redirects so an unexpected redirect cannot move the screening request to another origin. Read the response stream with a size limit, then validate the parsed envelope. A resolved fetch promise is not sufficient: inspect HTTP status and the screening status separately.
node screen.mjs request.jsonChange to the required production coverage
The production example selects ofac-sdn only. Add ofac-non-sdn only when your required scope includes it, after checking current availability and compatibility. An SDN-only check is not a complete non-SDN check, and non-SDN records do not all have the same restrictions.
For an authorized production operation, replace the package field with the sources array shown below, supply the actual lawfully held subject details, use a live key, and set ALLOW_LIVE_SCREENING=yes. Keep the complete request in request.json and create a new operation ID. Do not send both sources and package. The fragment below is a coverage change, not a complete request.
{
"sources": [
"ofac-sdn"
]
}Preserve the source details a reviewer needs
Preserve source record IDs, list names, program context, aliases, date precision, and the actual fields that support or conflict with a candidate. A no-match result does not resolve OFAC’s 50 Percent Rule, geography-based restrictions, or the legality of a proposed activity.
Retain the screening ID with your internal subject reference. Retrieve the complete evidence through the documented retained-result workflow when authorized; the console summary deliberately does not print raw identity details. A later analyst decision must not overwrite the original screening outcome.
Handle failures and test the source-specific edge cases
Treat HTTP errors, timeouts, malformed JSON, missing fields, unknown statuses, and unavailable required coverage as incomplete checks. A 401 or 403 needs credential or scope correction. A 409 needs idempotency-conflict handling. A 429 needs its specific rate-limit or usage-cap treatment; it is not a no-match result.
Test similar names with different reliable birth years, overlapping year-only dates, and a source record with no comparable identifier. The absence of an identifier is unknown, not a conflict.
In a Node test, stub the HTTP transport at the module boundary and include a response whose JSON parses but whose data.matches value is an object. It must fail rather than become an empty candidate list.
- Verify both valid result states and inconsistent status/matches combinations.
- Retry an accepted operation only with its original key and unchanged payload.
- Keep missing identity facts unknown instead of inventing contradictory values.
- Route potential matches into review before the separate business decision.
- Keep secrets, submitted names, and raw error bodies out of routine logs.