JavaScript / TypeScript
Send logs, exceptions, metrics, heartbeats and deployments from Node.js, Bun, Deno, browsers and edge runtimes with @incidion/sdk.
@incidion/sdk runs on Node.js 18+, Bun, Deno, browsers, Cloudflare Workers and Vercel Edge. It has no runtime dependencies (it uses the global fetch), ships ESM and CommonJS builds with TypeScript types, and sends logs and metrics in the background. All durations are in milliseconds.
Install
The package is not on npm yet. Build it from a clone of the repository and install the folder:
git clone https://github.com/nad3rk/incidion.git
cd incidion/sdks/javascript
npm install && npm run build
# then, in your app
npm install /path/to/incidion/sdks/javascript
Or build a tarball, for example for a Docker build or CI:
cd incidion/sdks/javascript
npm install && npm pack # writes incidion-sdk-0.1.0.tgz
cd /path/to/your-app
npm install /path/to/incidion-sdk-0.1.0.tgz
npm install github:nad3rk/incidion does not work, because the SDK lives in a subdirectory. Once published, it is npm install @incidion/sdk.
Quick start
import { Incidion } from '@incidion/sdk';
const incidion = new Incidion({
apiKey: process.env.INCIDION_API_KEY, // pk_... from Settings > API Keys
service: 'checkout-api',
});
incidion.info('User signed in', { user_id: 'u_123', method: 'passkey' });
try {
await chargeCard(order);
} catch (err) {
incidion.captureException(err, { request_id: req.id });
}
// At shutdown: deliver what is still queued (waits 5 s at most)
await incidion.close();
CommonJS: const { Incidion } = require('@incidion/sdk');.
Configuration
| Option | Env var | Default | Description |
|---|---|---|---|
apiKey |
INCIDION_API_KEY |
Public key pk_...: logs, metrics, heartbeats by monitor UUID |
|
secretKey |
INCIDION_SECRET_KEY |
Secret key sk_...: deployments only. Never in browser code |
|
projectId |
INCIDION_PROJECT_ID |
Project UUID, needed for deployments | |
baseUrl |
INCIDION_BASE_URL |
https://ingest.incidion.dev |
Ingest host |
apiUrl |
INCIDION_API_URL |
derived | API host for heartbeats and deployments, see below |
service |
INCIDION_SERVICE |
Default service of every log |
|
environmentId |
INCIDION_ENVIRONMENT_ID |
UUID of an Incidion environment, sent with every batch | |
release |
INCIDION_RELEASE |
App version, added to every log’s attributes as release |
|
host |
machine host name | Default host of metrics ("browser" in browsers) |
|
flushInterval |
5000 |
Milliseconds between background flushes | |
batchSize |
50 |
Logs per request; a full batch is sent at once | |
maxQueueSize |
10000 |
Most logs and metrics waiting; beyond it the oldest are dropped | |
maxRetries |
5 |
Retries of a batch the ingest could not take | |
maxRetryDelay |
300000 |
Longest wait in ms before sending again; also caps Retry-After |
|
beforeSend |
(entry) => entry | null: change or drop each log |
||
sampleRate |
1 |
Fraction (0 to 1) of logs below error that are kept |
|
debug |
false |
SDK diagnostics on the console (console.debug) |
|
captureUncaught |
false |
Report uncaught exceptions and unhandled rejections | |
flushOnExit |
true |
Flush on Node’s beforeExit and the browser’s pagehide |
|
fetch |
global fetch |
A custom fetch implementation |
At least one of apiKey and secretKey is required; the constructor throws IncidionError otherwise, and also when environmentId is set but not a UUID (the ingest would reject every batch). Environment variables are read only where the runtime has process.env (Node, Bun, Deno); in browsers and Workers pass the options explicitly.
apiUrl defaults to https://api.incidion.dev, to https://staging.incidion.dev for the staging ingest (https://ingest.staging.incidion.dev), and otherwise to baseUrl (self-hosted). A trailing /api/v1 is removed. Logs go to the environment of the key unless environmentId is set.
Keys
// In your app (server, browser, worker): the public key only
const incidion = new Incidion({ apiKey: 'pk_...' });
// In CI, for deployments: only the secret key
const ci = new Incidion({
secretKey: process.env.INCIDION_SECRET_KEY,
projectId: process.env.INCIDION_PROJECT_ID,
});
Without a pk_ apiKey, logs and metrics are dropped with one console warning. An sk_ key passed as apiKey still works for deployments, but the SDK warns that logs need the pk_ key. If a secret key is set in a browser, the SDK prints a loud console error: rotate that key in Incidion.
Logs
incidion.log('info', 'Order placed', { order_id: 'o_42' });
incidion.debug('Cache miss', { key: 'user:42' });
incidion.info('Payment captured');
incidion.warning('Retrying webhook', { attempt: 3 }); // incidion.warn() works too
incidion.error('Card declined', { user_id: 'u_123' });
incidion.critical('Database unreachable');
The second argument takes the ingest’s log columns by name: service, logger, request_id, trace_id, span_id, user_id, session_id, http_method, http_path, http_status, http_duration_ms, ip_address, user_agent, error_type, error_message, stack_trace, file_name, line_number, function_name. Every other key goes into the log’s attributes, as does an attributes object:
incidion.info('GET /orders', {
http_method: 'GET',
http_path: '/orders',
http_status: 200,
http_duration_ms: 37,
region: 'eu-west-1', // attributes.region
attributes: { cart: { items: 3 } },
});
Each log gets timestamp (ISO 8601, UTC), level, message, sdk_name (incidion-js) and sdk_version. On servers the attributes also hold runtime, runtime_version, hostname, pid and os. Level names such as warn, fatal and trace are mapped to Incidion’s five levels.
Exceptions
try {
await sync();
} catch (err) {
incidion.captureException(err, { request_id: 'req_1' });
}
incidion.error(new Error('also captured')); // error() with an Error does the same
captureException logs at level error with error_type (the error’s name), error_message and stack_trace, including the cause chain. Fields you pass override the ones the SDK fills in.
Context: tags, user, release, environment
incidion.setTags({ team: 'payments', region: 'eu' }); // merged into every log's attributes
incidion.setTag('tier', 'gold');
incidion.setTag('tier', null); // remove one
incidion.setTags(null); // remove all
incidion.setUser('u_123'); // user_id of every log; also { id: 'u_123' }
incidion.setUser(null);
release and environmentId are client options. A log’s own fields win over tags, and tags win over release and the runtime attributes. A user_id passed to a log wins over setUser. Tags apply to logs only, not to metrics.
beforeSend and sampling
const EMAIL = /[\w.+-]+@[\w-]+\.[\w.-]+/g;
const incidion = new Incidion({
apiKey: 'pk_...',
sampleRate: 0.25, // keep a quarter of debug/info/warning logs; every error and critical
beforeSend(entry) {
if (entry.http_path === '/healthz') return null; // drop
entry.message = entry.message.replace(EMAIL, '[email]');
for (const [key, value] of Object.entries(entry.attributes ?? {})) {
if (typeof value === 'string') entry.attributes![key] = value.replace(EMAIL, '[email]');
}
return entry;
},
});
beforeSend runs on the finished entry right before it is queued. Return null or false to drop it; return the entry (changed or a new object) to keep it. Returning nothing keeps the entry with any changes made in place. If it throws, the entry is sent unchanged and the SDK reports the error once on the console.
OpenTelemetry trace correlation
When a log has no trace_id or span_id and an OpenTelemetry span is active, the SDK fills both from that span (lowercase hex). It reads the global that @opentelemetry/api 1.x registers, so it does not depend on the package. Without OpenTelemetry, or without a registered context manager (for example @opentelemetry/sdk-node, or AsyncLocalStorageContextManager), nothing is added.
import { trace } from '@opentelemetry/api';
const tracer = trace.getTracer('checkout');
await tracer.startActiveSpan('charge', async (span) => {
incidion.info('Charging card'); // carries the span's trace_id and span_id
span.end();
});
Incidion stores logs, not traces. To export logs from an OpenTelemetry setup directly, see OpenTelemetry.
Frameworks and runtimes
Express
import express from 'express';
import { Incidion } from '@incidion/sdk';
const incidion = new Incidion({ service: 'shop-api', release: process.env.GIT_SHA });
const app = express();
// Every request
app.use((req, res, next) => {
const started = performance.now();
res.on('finish', () => {
incidion.log(res.statusCode >= 500 ? 'error' : 'info', `${req.method} ${req.path}`, {
request_id: req.get('x-request-id'),
http_method: req.method,
http_path: req.path,
http_status: res.statusCode,
http_duration_ms: Math.round(performance.now() - started),
ip_address: req.ip,
user_agent: req.get('user-agent'),
});
});
next();
});
// ... your routes ...
// Errors: after the routes, with four arguments
app.use((err, req, res, next) => {
incidion.captureException(err, {
http_method: req.method,
http_path: req.path,
request_id: req.get('x-request-id'),
});
next(err);
});
const server = app.listen(3000);
process.on('SIGTERM', () =>
server.close(async () => {
await incidion.close();
process.exit(0);
}),
);
Next.js
Create the client once in a module and import it where needed:
// lib/incidion.ts
import { Incidion } from '@incidion/sdk';
export const incidion = new Incidion({
apiKey: process.env.INCIDION_API_KEY,
service: 'web',
release: process.env.VERCEL_GIT_COMMIT_SHA,
});
Errors of every route, page and server action go through onRequestError in instrumentation.ts (Next.js 15+):
// instrumentation.ts
import type { Instrumentation } from 'next';
import { incidion } from './lib/incidion';
export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
incidion.captureException(err, {
http_method: request.method,
http_path: request.path,
route: context.routePath,
});
await incidion.flush();
};
In a route handler, flush after the response with after:
// app/api/orders/route.ts
import { after } from 'next/server';
import { incidion } from '@/lib/incidion';
export async function POST(request: Request) {
after(() => incidion.flush());
const order = await createOrder(await request.json());
incidion.info('Order placed', { order_id: order.id, http_method: 'POST', http_path: '/api/orders' });
return Response.json(order, { status: 201 });
}
On serverless hosts the function may be frozen as soon as the response is sent, so every invocation that logs should end with a flush (after, or waitUntil from @vercel/functions). In client components, use a separate browser client with the pk_ key (see Browser).
Cloudflare Workers and Vercel Edge
Workers stop running once the response is sent unless you hand them a promise. Create the client once per isolate and pass flush() to ctx.waitUntil on each request:
import { Incidion } from '@incidion/sdk';
let incidion: Incidion | undefined;
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
incidion ??= new Incidion({ apiKey: env.INCIDION_API_KEY, service: 'edge-api' });
try {
const response = await handle(request);
incidion.info('request', {
http_method: request.method,
http_path: new URL(request.url).pathname,
http_status: response.status,
});
return response;
} catch (err) {
incidion.captureException(err);
return new Response('error', { status: 500 });
} finally {
ctx.waitUntil(incidion.flush());
}
},
};
Store the key with wrangler secret put INCIDION_API_KEY. On Vercel Edge Functions, use waitUntil(incidion.flush()) from @vercel/functions. The SDK starts no timers until the first log, so creating the client in module scope is fine.
Browser
import { Incidion } from '@incidion/sdk';
export const incidion = new Incidion({
apiKey: 'pk_...', // only ever the public key in the browser
service: 'web',
release: import.meta.env.VITE_RELEASE,
captureUncaught: true,
sampleRate: 0.2,
});
incidion.setUser(currentUser.id);
incidion.metric('web.lcp', lcp, { unit: 'ms', tags: { page: location.pathname } });
When the page is hidden or unloaded (visibilitychange to hidden, and pagehide), queued logs and metrics are sent with fetch(..., { keepalive: true }), up to the browser’s 64 KiB keepalive budget; the rest goes with the next flush if the page stays open. Browsers send a CORS preflight first, because the SDK sets an X-API-Key header; the ingest allows any origin by default. Anyone can read a key in browser code, which is why only the pk_ key belongs there: it can send logs and metrics and nothing else.
Uncaught errors
With captureUncaught: true:
- Node, Bun, Deno:
uncaughtExceptionis logged ascriticalandunhandledRejectionaserror, withattributes.mechanism. If your app has no handler of its own, the SDK keeps Node’s behaviour: it prints the error, delivers the logs (2 s at most) and exits with code 1. The--unhandled-rejectionsmode is respected (warnandnonedo not exit). - Browsers:
windowerrorandunhandledrejectionevents are logged aserror, with the script’sfile_nameandline_number.
Bun and Deno
These work like Node. Deno imports the built file until the package is on npm (then npm:@incidion/sdk), and needs --allow-net for the ingest host; --allow-env and --allow-sys are optional and let the SDK read INCIDION_* variables and the host name.
Metrics
incidion.metric('queue.depth', 42);
incidion.metric('http.latency', 87.5, { unit: 'ms', tags: { route: '/orders' } });
incidion.metric('disk.used', 71, { unit: 'percent', host: 'db-1' });
metric(name, value, { unit, tags, host }) queues one value. Metrics are sent to /v1/metrics in requests grouped by host and tags, with the same retries as logs. The host defaults to the host option, then the machine’s host name ("browser", "cloudflare-workers" or "vercel-edge" where there is none). Values that are not finite numbers are dropped; tag values are sent as strings.
Heartbeats
Copy the heartbeat URL of a monitor in Incidion. Pass the URL or its hb_ token; neither needs a key.
const HEARTBEAT = 'https://api.incidion.dev/api/v1/heartbeat/hb_xxxxxxxx/';
await incidion.heartbeat(HEARTBEAT); // up
await incidion.heartbeat('hb_xxxxxxxx', { status: 'degraded', message: 'Slow run' });
await incidion.heartbeatStart(HEARTBEAT); // job started
heartbeat and heartbeatStart resolve to true when Incidion recorded the ping. They never throw: a failure resolves to false and is printed on the console.
For jobs, withHeartbeat runs a function and reports the result:
// jobs/backup.mjs, run by cron: 0 3 * * * node /opt/jobs/backup.mjs
import { Incidion } from '@incidion/sdk';
const incidion = new Incidion({ service: 'backup' });
await incidion.withHeartbeat(process.env.BACKUP_HEARTBEAT_URL, async () => {
await backupDatabase();
}, { sendStart: true });
await incidion.close();
With sendStart, the start is reported first, so Incidion records the run time. The function succeeding pings up. When it throws, withHeartbeat pings down with the error message, logs the error with captureException and rethrows. It resolves to the function’s return value. More on monitors: Heartbeats.
Deployments from CI
Deployments need the project’s secret key (secretKey or INCIDION_SECRET_KEY), projectId, and the Pro plan or higher. Run them in CI, never in app code.
// scripts/deploy.mjs: node scripts/deploy.mjs ./deploy.sh
import { spawnSync } from 'node:child_process';
import { Incidion, IncidionError } from '@incidion/sdk';
const incidion = new Incidion(); // INCIDION_SECRET_KEY and INCIDION_PROJECT_ID
const env = process.env;
const repo = `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}`;
let id;
try {
id = await incidion.deploymentStart({
version: env.GITHUB_SHA.slice(0, 7),
environment: 'production', // slug of an Incidion environment
commitHash: env.GITHUB_SHA,
branch: env.GITHUB_REF_NAME,
runUrl: `${repo}/actions/runs/${env.GITHUB_RUN_ID}`,
repositoryUrl: repo,
deployedByName: env.GITHUB_ACTOR,
trigger: 'ci',
});
} catch (err) {
if (!(err instanceof IncidionError)) throw err;
console.error(`Incidion: deployment not recorded: ${err.message}`); // PlanLimitError included
}
const result = spawnSync(process.argv[2], { stdio: 'inherit' });
const ok = result.status === 0;
if (id) {
await incidion.deploymentFinish(id, ok
? { status: 'success' }
: { status: 'failed', errorMessage: `exit code ${result.status}` });
}
process.exit(result.status ?? 1);
# .github/workflows/deploy.yml (the SDK installed as described under Install)
- run: node scripts/deploy.mjs ./deploy.sh
env:
INCIDION_SECRET_KEY: ${{ secrets.INCIDION_SECRET_KEY }}
INCIDION_PROJECT_ID: ${{ vars.INCIDION_PROJECT_ID }}
deploymentStart takes version (required), environment, commitHash, commitMessage, branch, runUrl, repositoryUrl, changes ([{ type, message }]), deployedByName and trigger ('ci', 'manual' or 'rollback'), and resolves to the deployment id. deploymentFinish(id, { status, errorMessage, buildSteps }) takes success (default), failed or rolled_back and buildSteps as [{ name, status, duration_seconds }]; it resolves to the deployment. See Deployments.
Flush and close
await incidion.flush(); // send now; never rejects
const undelivered = await incidion.close(5000); // flush, stop, resolve to the number of logs and metric values not delivered
Timers never keep a Node, Bun or Deno process alive. On Node’s beforeExit the SDK closes itself, so a script that ends on its own still delivers its logs. process.exit() and signals skip beforeExit, so close first:
process.on('SIGTERM', async () => {
await incidion.close();
process.exit(0);
});
- Serverless functions (AWS Lambda, Vercel, Netlify):
await incidion.flush()before the handler returns, or hand it towaitUntil/after. - Workers and queues:
await incidion.close()in the shutdown handler. - CLI scripts: nothing to do if the script ends on its own;
await incidion.close()before anyprocess.exit().
Delivery
- Logs are sent every
flushIntervalms, or at once whenbatchSizeare waiting. Each request holds at mostbatchSizelogs and times out after 30 s. 429and503(rate limit, daily quota, ingest busy): nothing is sent until the server’sRetry-After, capped bymaxRetryDelay. Then the batch is sent again, followed by everything that queued up meanwhile.502,504and network errors: retried after 2, 4, 8, 16, then 30 s, up tomaxRetries, then dropped with a console error.413: the batch is split in halves and each half is sent on its own.- Other
4xx(for example a revoked key): the batch is dropped and reported on the console, not retried. Rows the ingest rejects one by one are printed with their reason (the first 5). - More than
maxQueueSizelogs and metrics waiting: the oldest are dropped.
close(timeoutMs = 5000) waits at most timeoutMs in total. It makes one last attempt even while the server asked to wait, then drops what is left with one console error, and resolves to the number of logs and metric values it could not deliver. Logging after close() is ignored. SDK diagnostics go to the console ([incidion] ...), never through your own logging, so nothing can loop.
Errors
| Call | On failure |
|---|---|
new Incidion(...) |
throws IncidionError when neither key is set or environmentId is not a UUID |
Logs, metrics, flush |
never throw; problems are printed on the console |
heartbeat, heartbeatStart |
never throw; resolve to false |
withHeartbeat |
rethrows the function’s error |
deploymentStart, deploymentFinish |
reject with PlanLimitError or IncidionError |
import { IncidionError, PlanLimitError } from '@incidion/sdk';
try {
await incidion.deploymentStart({ version: '1.4.0' });
} catch (err) {
if (err instanceof PlanLimitError) {
console.error(err.message, err.upgradeRequired, err.upgradeUrl);
} else if (err instanceof IncidionError) {
console.error(err.status, err.code, err.message, err.details);
}
}
PlanLimitError extends IncidionError (HTTP 403 PlanLimitExceeded) and adds planLimit, upgradeRequired and upgradeUrl. IncidionError covers a missing secretKey or projectId, a wrong key (401), an invalid request (400, with details), other HTTP errors and network errors.
Troubleshooting
The console shows 401 from the ingest, or a warning that apiKey is a secret key. Logs and metrics need the public key (pk_...). Pass the sk_ key as secretKey (CI only) and the pk_ key as apiKey.
PlanLimitError from deploymentStart. The organization is on the Free plan; deployments need Pro or higher. See Plans and Limits.
Nothing arrives from a Lambda, a Worker or a script that calls process.exit(). The runtime stopped before the background flush. await incidion.flush() (serverless), ctx.waitUntil(incidion.flush()) (Workers) or await incidion.close() (before process.exit()).
Still nothing. Set debug: true: each request with its HTTP status and every batch flushed is printed with console.debug (in browsers, enable the Verbose level in the console). Warnings and errors (rejected rows, retries, dropped batches) are printed even without debug.