Trasys
Node.js SDK

Installation & Setup

Install the Trasys SDK with npm and create a dedicated initializer file that must be required before any other library so instrumentation patches load first.

Installation & Setup

Install the package

npm install @trasys/sdk

Create the initializer file

The SDK must be initialized before any other library is imported. The standard pattern is a dedicated file — typically trasys.js or trasys.ts at the root of your project — that you require first in your entry point.

The SDK patches database and HTTP libraries at load time. If a library loads before sdk.init() runs, it will not be instrumented. Always require your initializer file before everything else.

trasys.js (CommonJS)

const { createSdk } = require('@trasys/sdk');

const { sdk, logger, monitor } = createSdk({
  apiKey:      process.env.TRASYS_API_KEY,
  service:     process.env.SERVICE_NAME,
  environment: process.env.NODE_ENV ?? 'development',
});

module.exports = { sdk, logger, monitor };

trasys.ts (TypeScript / ESM)

import { createSdk } from '@trasys/sdk';

export const { sdk, logger, monitor } = createSdk({
  apiKey:      process.env.TRASYS_API_KEY,
  service:     process.env.SERVICE_NAME,
  environment: process.env.NODE_ENV ?? 'development',
});

Require it first in your entry point

// index.js — correct import order
require('dotenv').config();
const { sdk, logger } = require('./trasys'); // ← must come first

const express = require('express');
const { Pool }  = require('pg');              // ← after SDK

createSdk returns three objects:

FieldTypeDescription
sdktrasysThe SDK instance — middleware, wrappers, health checks
loggerLoggerStructured logger — see Logging
monitorMonitorCustom metrics — counters, gauges, histograms

Configuration reference

All fields are optional when the corresponding environment variable is set.

createSdk({
  // ── Identity ────────────────────────────────────────────
  apiKey:      process.env.TRASYS_API_KEY,
  service:     'payment-service',
  environment: 'production',
  version:     process.env.npm_package_version,

  // ── Destination ─────────────────────────────────────────
  endpoint: 'https://ingest.trasys.dev', // override for self-hosted

  // ── User attribution ────────────────────────────────────
  userIdPath:   'user.id',       // dot-path into req object
  tenantIdPath: 'user.tenantId',

  // ── Sampling ────────────────────────────────────────────
  sampling: {
    default:                1.0,   // record all requests
    routes: {
      '/api/health':        0.01,  // noisy — sample 1%
      '/api/search':        0.10,  // high volume — sample 10%
    },
    alwaysRecordErrors:     true,  // always record 4xx/5xx
    slowRequestThresholdMs: 3000,  // always record requests > 3s
    alwaysRecordUserIds:    [],    // debug specific users at 100%
  },

  // ── AI capture ──────────────────────────────────────────
  ai: {
    capturePrompts:    true,  // AES-256-GCM encrypted
    captureResponses:  true,
    maskFields:        ['ssn', 'card_number'],
    maxContentLength:  10000,
  },

  // ── Database ────────────────────────────────────────────
  database: {
    captureQueries:       true,
    slowQueryThresholdMs: 1000,
    maskColumns:          ['password', 'token', 'secret'],
  },

  // ── Session tracking ────────────────────────────────────
  session: {
    source:     'auto',        // 'auto' | 'jwt' | 'cookie' | 'header' | 'none'
    cookieName: 'connect.sid',
    headerName: 'authorization',
  },

  // ── Route filtering ─────────────────────────────────────
  ignoreRoutes: ['/health', '/healthz', '/ping', '/metrics', '/favicon.ico'],

  // ── Auto-instrumentation ────────────────────────────────
  autoInstrument: {
    express:       true,
    fastify:       true,
    mongoose:      true,
    mongodbDriver: false, // use only when mongoose: false
    prisma:        true,
    drizzle:       true,
    sequelize:     true,
  },

  debug: false, // verbose startup logging — never enable in production
});

Environment variables

You can configure the SDK entirely via environment variables — useful for containerized deployments.

VariableEquivalent field
TRASYS_API_KEYapiKey
TRASYS_SERVICEservice
TRASYS_ENVIRONMENTenvironment
TRASYS_VERSIONversion
TRASYS_ENDPOINTendpoint
TRASYS_DEBUGdebug
NODE_ENVenvironment (fallback)
npm_package_versionversion (fallback)

API key validation

At startup the SDK validates the API key format (no network call), then verifies it with the ingest service in the background.

EnvironmentBehavior on invalid key
Development / stagingCrashes the process immediately — catch bad keys before production
ProductionOpens a circuit — stops collecting data, logs one error, does not crash

Set TRASYS_SKIP_KEY_VALIDATION=true to bypass validation during local development or testing.


Graceful shutdown

The SDK registers handlers for SIGTERM, SIGINT, and beforeExit. On shutdown it flushes all buffered events before the process exits. In most cases you do not need to call sdk.shutdown() manually.

For custom shutdown flows:

process.on('SIGTERM', async () => {
  await sdk.shutdown();
  process.exit(0);
});

Next steps

On this page