Skip to content

Node

Trace every request your Node server handles and every call it makes, without OpenTelemetry, send them as OTLP, link them to the browser session that caused them, and report server errors, with one import.

Applies to EngineCloud
View as Markdown
On this page
  1. Install
  2. Check that it works
  3. What is traced without any code
  4. Database error details
  5. When a call has failed
  6. Requests that never finish
  7. Linking the browser to the server
  8. What it sends, and where
  9. init(options)
  10. Errors
  11. The functions you call
  12. reportError(error)
  13. identify(who)
  14. span(name, fn, attrs?)
  15. activeSpan() and setSpanAttributes(values)
  16. flush(timeoutMs?) and shutdown(timeoutMs?)
  17. wrapFetchHandler(handler)
  18. traceRequest(request, handle, options?)
  19. Graceful shutdown
  20. Serverless and other runtimes
  21. What it costs
  22. What was measured
  23. Measured on this SDK
  24. Next

This page is for whoever runs a Node server: an API, a backend for a web app, a server-rendered site. @sypnia/telemetry/node is open source (MIT) and identical for the open-source engine and for Sypnia Cloud; only the address and the origin of the key differ. For Next.js use @sypnia/telemetry/next, which includes this.

It is Sypnia’s own tracer, small on purpose: it does not depend on OpenTelemetry and installs no module loader. What it sends is standard, though: traces in the OpenTelemetry protocol (OTLP/HTTP, protobuf), with OpenTelemetry’s attribute names and a few sypnia.* ones, listed in the semantic conventions. If your app already uses OpenTelemetry, or you want its instrumentations for more libraries, use the OpenTelemetry bridge instead.

At the end you will have: every incoming request traced without placing any call by hand, its database and service calls as spans, server errors as problems, and each trace joined to the browser session that started it.

Install

npm

npm install @sypnia/telemetry

Create one file that starts Sypnia, and import it before anything else in your server’s entry file.

Sypnia Cloud

src/instrument.ts
import { init } from '@sypnia/telemetry/node';

init({
  project: process.env.SYPNIA_PROJECT_KEY,
  service: 'shop-api',
  environment: process.env.SYPNIA_ENVIRONMENT ?? 'production',
  release: process.env.SYPNIA_RELEASE,
});
src/server.ts
import './instrument';
import express from 'express';

const app = express();
app.post('/api/checkout', checkout);
app.listen(3000);
.env
SYPNIA_PROJECT_KEY=spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e
SYPNIA_ENVIRONMENT=production
SYPNIA_RELEASE=4f2a91c

Use the same project as your frontend, and the same environment and release naming. A trace connects parts of one project in one environment.

Check that it works

  1. Start your server with debug: true in init.
  2. Call any route: curl -i http://localhost:3000/api/checkout -X POST.
  3. The console prints the request as a tree of spans, then one line per call (for the shop’s checkout: POST /api/checkout 400 · 3,842 ms, SELECT carts, POST /v1/payments), and within 2 seconds exported 3 spans (200).

What is traced without any code

WhatCoversBecomesHow
Incoming requestsEvery request to a server built on Node’s http or https module: Express, Fastify, Koa, NestJS, Hono on Node, plain http.A server span (SPAN_KIND_SERVER) with method, path, route, status and duration.Node’s own http.server.request.start diagnostics channel, and the response’s finish and close events. The request’s context lives in an AsyncLocalStorage.
Outgoing HTTP callsfetch, and http.request / https.request (so also axios, got and most SDKs).A client span of kind http, named POST /v1/payments.The diagnostics channels Node publishes for http clients and for fetch (undici). No function of yours is wrapped; the platform’s fetch is, only to read database errors.
Postgres queriesThe pg package.A client span of kind db, named by operation and table: SELECT carts. Never the statement’s values.init finds pg in your app’s dependencies and wraps Client.prototype.query once. Pools use the same client, so they are covered.
Supabase and PostgREST callsRecognized among the outgoing calls by their path (/rest/v1/…).A client span of kind db: SELECT orders, INSERT orders, CALL create_order, with sypnia.db.via postgrest. A PUT, PostgREST’s upsert, is named INSERT.Read from the outgoing call’s method and path, and, when the call fails, from its answer: see Database error details.
ErrorsListed under Errors.An exception event on the span where it happened, or a failed span.Process handlers for uncaught exceptions and unhandled rejections; the request’s own span for the rest.

Other database drivers (MySQL, MongoDB, Redis, Prisma’s own engine) are not traced by themselves. Wrap the call in span(), or use their OpenTelemetry instrumentation through the bridge, at OpenTelemetry’s cost.

Not traced by default: OPTIONS requests, and requests for static files (a path that ends in .js, .css, .map, .png, .jpg, .jpeg, .gif, .svg, .ico, .webp, .avif, .woff, .woff2, .ttf, .txt, .xml or .webmanifest). Add your health check with ignoreRoutes.

Never read: request bodies, the answers of calls that succeeded, cookies, headers other than traceparent and x-sypnia-session, and query strings. A span’s name and attributes carry the method, the host, the path and the status, nothing else: url.query, url.full and db.query.text are never sent. There is one exception, on by default: what the database answers when a database call returns an error, described next.

Database error details

When a database call answers with an error, the SDK reads what the database said. It is the only answer the SDK reads.

CallWhat is readWhat is kept
A Supabase or PostgREST call through fetch answered 400 or aboveThe first 4 KB of a copy of the answer’s body. Your code still reads the whole body, as beforecode, and message with details and hint on lines of their own, as PostgREST wrote them
A pg query that throwsThe error pg gives your codeIts SQLSTATE, and its message with its detail and hint on lines of their own, as Postgres wrote them

The code goes to db.response.status_code: the SQLSTATE, such as 22P02, or PostgREST’s own code, such as PGRST116. The message goes to sypnia.db.message, up to 2,000 characters, as message, then Detail: … and Hint: … on their own lines when the database sent them (the way psql prints an error), and when the call failed (no answer, 400, 500 or above, or a pg error) it is also the span’s status message. An answer such as 404 or 409 is not a failure: the span stays ok and carries the code and the message as attributes. Nothing in the message is replaced. When the shop’s code looks up an order with an e-mail where an id belongs, the span’s message is:

Text
invalid input syntax for type uuid: "maria@example.com"

When a customer signs up with an e-mail that already has an account, the database puts the value in the detail:

Text
duplicate key value violates unique constraint "users_email_key"
Detail: Key (email)=(maria@example.com) already exists.
  • It can contain personal data. Whatever the database puts in its message is sent as it is: an e-mail, a name, an amount or an id from the call that failed. It is stored with the trace and the problem, and everyone who can read the project sees it.
  • It is on by default, because the exact message, with its value, is what tells you what failed.
  • A successful answer is never read, whatever the setting.
  • Grouping still works. A failed database call’s fingerprint uses its code and the first line of its message, normalized as for every error (quoted values, numbers, UUIDs and URLs are replaced first), so the values in a message and its Detail: and Hint: lines do not split a problem. A problem’s title carries the code, never the message. See Problem grouping.
  • The agent’s analysis gets the message after its own redaction, which replaces e-mail addresses, long numbers and tokens and leaves other values: see Models and what is sent.
  • At the end of a request the SDK waits at most 50 ms for an error body still being read.
  • Not covered: PostgREST called through http.request (Supabase’s client uses fetch), and a Supabase client created with a fetch your code captured before init ran.

Reading those answers is the one place where the SDK wraps a function: the platform’s globalThis.fetch, because Node publishes no body on its diagnostics channels. Your own functions are never wrapped, and properties frameworks put on fetch are kept.

To keep these details out, set captureDbErrors: false in init:

src/instrument.ts
import { init } from '@sypnia/telemetry/node';

init({
  service: 'shop-api',
  captureDbErrors: false,
});

Then no answer is read at all: a failed Supabase or PostgREST call carries its HTTP status as its code and no message, and a failed pg query keeps its SQLSTATE, which holds no value, and no message.

When a call has failed

A call your server makes has failed when it gets no answer, answers 400, or answers 500 or above. A request your server receives has failed when it answers 500 or above, or throws. Answers such as 401, 404 and 409 are answers, not failures.

Requests that never finish

A request still running after 20 seconds is exported at that moment as a partial span (sypnia.partial): the spans that finished, and the calls still in flight marked sypnia.running. If the request finishes, the SDK exports the same span again in full and it replaces the partial one. If the platform kills it, the partial span is what you have, and when no full span has come 15 minutes later it becomes a timeout problem. Change the threshold with slowRequestMs.

Linking the browser to the server

The browser SDK adds two headers to calls to your API. The Node SDK reads them, so you do nothing:

HeaderRead as
traceparentThe trace id and the parent span: the server span takes the browser call’s span id as parentSpanId, so the server’s spans join the browser’s trace. Without it, the server starts a new trace.
x-sypnia-sessionThe session id, sent as the attribute session.id. The request appears in that session’s timeline, and its failures count for the person of that session.

On every outgoing call, the SDK adds traceparent with the current trace, so the next service continues it: another Node server with this SDK, or any backend with an OpenTelemetry SDK. It never forwards x-sypnia-session, and it never replaces a traceparent your code already set. On a Node 20 release that does not publish the http.client.request.created diagnostics channel, calls made with http.request (and the libraries built on it) cannot be given traceparent; fetch calls can.

If the browser calls your API on another origin, the API must allow both headers in CORS. See Browser.

What it sends, and where

Every 2 seconds, and at the end of a serverless invocation, the SDK exports the spans of the requests that finished: one OTLP/HTTP request, in protobuf, gzipped, to <endpoint>/v1/otlp/v1/traces, with the ingest key in Authorization. At most 512 spans per export, and the spans of one request always travel together. While the engine cannot be reached, at most 5,120 spans wait in memory; past that, the oldest requests without a failure are dropped first. A failed export is retried after 1, 4 and 15 seconds, only after a network error or a 429, 502, 503 or 504 answer, and never sooner than the answer’s Retry-After, counted up to 60 seconds. It is the same endpoint any OpenTelemetry exporter can use, so you can point a Collector or a debugging proxy at it and read what the SDK sends with ordinary tools.

On the wireFrom
Resource service.name, deployment.environment.name, service.versionservice, environment, release in init
Server span: http.request.method, http.route, url.path, http.response.status_codeThe request
session.id, user.id, sypnia.account.idx-sypnia-session, and identify()
Client spans: server.address, url.path, db.system.name, db.operation.name, db.collection.nameThe calls
db.response.status_code, sypnia.db.messageDatabase error details
exception events, status ERROR with its message: a database’s as it wrote it, any other redactedErrors

The full list, with types and examples, is the semantic conventions.

init(options)

OptionTypeDefaultWhat it does
projectstringprocess.env.SYPNIA_PROJECT_KEYThe ingest key, spk_…. Without it the SDK does nothing and prints one warning.
endpointstringprocess.env.SYPNIA_ENDPOINT, else 'https://telemetry.ingest.sypnia.com'Where to send. A self-hosted engine’s base URL.
servicestring, up to 80 charactersprocess.env.SYPNIA_SERVICE, else 'server'The name of this service in traces.
environmentstring, 1 to 40 charactersprocess.env.SYPNIA_ENVIRONMENT, else 'production'The environment. Use the same names as the frontend.
releasestring, up to 40 charactersprocess.env.SYPNIA_RELEASE, else noneThe release. Use the short git commit.
enabledbooleantruefalse turns the SDK into a no-op.
debugbooleanfalsePrints every request as a tree of spans, and every export, to the console.
allowRoutes(string | RegExp)[]none: every pathWhen set, only these incoming paths are traced; requests to any other path are not. Same matching as ignoreRoutes, which still applies inside them. For apps that observe some areas only.
anonymousRoutes(string | RegExp)[]none0.3.0. Public paths traced without identity: identify() is ignored in their requests, which carry sypnia.anonymous = true. Traced even when allowRoutes does not list them. See Anonymous visitors.
ignoreRoutes(string | RegExp)[][]Incoming paths that are not traced, on top of the defaults above. A string matches the path and everything under it; a RegExp is tested against the path.
routeFor(pathname: string) => stringthe built-in ruleYour own way to turn a path into a route. By default the SDK uses the route pattern of Express and Fastify when it can read it (/orders/:id), and otherwise the same rule as the browser.
capture.outgoingbooleantrueSpans for outgoing HTTP calls.
capture.dbbooleantrueSpans for pg, and naming of Supabase and PostgREST calls.
pgthe pg modulenone: the SDK looks for pg from the working directoryThe pg module itself (import pg from 'pg'), for a bundled app, such as an AWS Lambda function bundled with esbuild, where pg is not in node_modules for the SDK to find. From 0.1.2.
captureDbErrorsbooleantrueReads the error answer of a database call and keeps its code and full message, values included, up to 2,000 characters. false: nothing is read; a pg error keeps only its SQLSTATE. See Database error details.
capture.consoleErrorsbooleantrueReports console.error during a request as a failure.
capture.uncaughtbooleantrueReports uncaught exceptions and unhandled rejections.
propagatebooleantrueAdds traceparent to outgoing calls.
slowRequestMsnumber20000When a request still running is reported as partial. 0 turns it off.
flushBudgetMsnumber50The longest the SDK waits for a send at the end of a serverless invocation.
beforeSend(span) => span | nullnoneCalled with each finished span (name, kind, attributes, status) before it is queued. Change it and return it, or return null to drop it; dropping a server span drops its request’s spans too.

Fixed limits: 200 spans kept per request (the rest are counted in sypnia.dropped_spans), 64 attributes per span, 5 failures per request of which 3 from console.error, one per fingerprint. They are in the semantic conventions.

Errors

Caught without codeHow it appears
An exception nobody caught, or an unhandled rejectionA failure with its stack: an exception event on the request’s span, or, outside any request, on a span of its own marked sypnia.error.standalone. The SDK watches through Node’s uncaughtExceptionMonitor, so what Node does next does not change. A rejection your app handles with its own unhandledRejection listener is not seen. When the process dies right after, the request in flight is sent at once as partial; that send is best effort.
A call that failed (see above)A failed span, which Sypnia names after the call, such as HTTP 400 or DB 23505. A failed HTTP call carries its status only: the SDK does not read its answer. A failed database call carries the database’s code and its full message, unless you turned that off: see Database error details. Any other message is redacted before it leaves your server: e-mail addresses, URLs, UUIDs, quoted values, long tokens and every run of digits are replaced.
A request answered with 500 or above, with no other failureA failure named HTTP 500, with the route.
console.error while handling a requestAn exception event with the logged text (sypnia.error.source log), and the stack if an Error was logged.

Frameworks catch errors thrown in your handlers and turn them into a 500. Sypnia then knows the request failed, and not why. Hand the error over with one line, so the problem has its stack:

Express

src/server.ts
import { reportError } from '@sypnia/telemetry/node';

// after all routes
app.use((error, req, res, next) => {
  reportError(error);
  next(error);
});

The functions you call

reportError(error)

Reports an error your code caught, as an exception event (sypnia.error.source manual). Inside a request it is attached to that request’s trace and session.

identify(who)

Says who a request belongs to. You need it only for requests that do not come from an identified browser session: a mobile app, an API client, a webhook. For the others, Sypnia already knows the person from the session.

src/auth-middleware.ts
import { identify } from '@sypnia/telemetry/node';

app.use((req, res, next) => {
  if (req.user) identify({ person: { id: req.user.id }, account: { id: req.user.accountId } });
  next();
});

It applies to the current request only: the server span gets user.id and sypnia.account.id. Only ids travel; names and e-mail addresses are never sent from the server. See Identifying people.

span(name, fn, attrs?)

Records your own step as a span of kind internal, around a function. It returns what the function returns, and marks the span failed if the function throws. The function receives the span, a handle with setAttribute(name, value) and setAttributes(values), to set attributes while it runs or after it ends.

src/checkout.ts
import { span } from '@sypnia/telemetry/node';

const total = await span('price cart', s => {
  const t = priceCart(cart);
  s.setAttribute('cart.discounted', t.discount > 0);
  return t;
}, { 'cart.items': cart.items.length });

name has at most 120 characters. Attribute values are strings of at most 256 characters, numbers or booleans; other values are left out.

activeSpan() and setSpanAttributes(values)

From version 0.4.0. They set attributes on the span the current code runs in: the span() being run, else the request’s or the job’s own span. You can still set them after the work ended, until the request is sent. That is how a use case carries sypnia.case from when it starts and sypnia.case.outcome from when it ends (Use cases and places).

src/checkout.ts
import { setSpanAttributes } from '@sypnia/telemetry/node';

setSpanAttributes({ 'sypnia.case': 'place-order' });
const order = await placeOrder(cart);
setSpanAttributes({ 'sypnia.case.outcome': 'OrderPlaced' });

setSpanAttributes returns false when there is no span to set (outside a traced request, or with the SDK off), and does nothing. activeSpan() returns the same handle span() gives its function; with no span, a handle that does nothing. sypnia.case is kept up to 128 characters and sypnia.case.outcome up to 80. In Next.js, import both from @sypnia/telemetry/next/server.

flush(timeoutMs?) and shutdown(timeoutMs?)

flush sends what is waiting and resolves when it is sent or after timeoutMs (default 2,000). shutdown does the same and then stops the SDK.

wrapFetchHandler(handler)

For runtimes where a server is a function from a Request to a Response. See Serverless.

traceRequest(request, handle, options?)

For framework integrations, not for apps: it traces one request on a host where no Node server announces requests, and runs handle inside it. wrapFetchHandler is built on it, and so is the OpenNext adapter of @sypnia/telemetry/next.

Custom events (track) are sent from the browser only.

Graceful shutdown

Finished spans wait in memory for up to 2 seconds before they are exported together, in one OTLP request. When your process is asked to stop, send them first:

src/server.ts
import { shutdown } from '@sypnia/telemetry/node';

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

The SDK flushes by itself when the event loop empties (beforeExit). It does not install signal handlers: that would change how your process stops.

Serverless and other runtimes

Where it runsWhat to do
A long-running Node server, Node 20 or newerimport './instrument' first. Everything on this page.
Next.js@sypnia/telemetry/next.
Functions written as (request: Request) => Response: Vercel Functions, Supabase Edge Functions, HonowrapFetchHandler, below.
Next.js on AWS Lambda through OpenNext (what SST’s Nextjs deploys)@sypnia/telemetry/next/opennext: Next.js, On AWS Lambda.
Your own AWS Lambda handlers: API Gateway or function URL events, SQS consumers, direct invokes, scheduled runswrapLambdaHandler and wrapSqsHandler: Queues and functions.
Bun, Deno and Cloudflare WorkerswrapFetchHandler uses only web-standard APIs and AsyncLocalStorage, so it may work there. Sypnia does not test on these.
api/checkout.ts
import { init, wrapFetchHandler } from '@sypnia/telemetry/node';

init({ project: process.env.SYPNIA_PROJECT_KEY, service: 'shop-api' });

export default wrapFetchHandler(async (request: Request) => {
  const order = await createOrder(await request.json());
  return Response.json(order);
});

wrapFetchHandler traces the request like any other and exports its spans after the response. Where the platform offers a way to keep working after the response (waitUntil), it uses it. Where it does not, it waits at most flushBudgetMs (50 ms) before returning the response; a send that takes longer goes on in the background and can be lost if the platform freezes the function.

A function that is frozen between invocations does not run timers. If you do not use wrapFetchHandler, call await flush() before you return.

What it costs

What was measured

On 2026-11-15 we measured what tracing costs a Node server, with a light tracer of our own (the design of this SDK, in its smallest form) and with the official OpenTelemetry Node SDK. One machine: a laptop under WSL2, Node 22. The server’s handler made two calls to a local service that answered after 2 ms, standing for a database and a payment API. Load: autocannon, 10 connections, 5 seconds of warm-up and 15 measured, about 1,400 requests a second. CPU per request is the process’s CPU time divided by the requests. Two runs; the numbers are their range.

No tracingLight own tracerOpenTelemetry Node SDK 2.12 (HTTP instrumentation, OTLP/HTTP JSON exporter, batch every 2 s)
CPU per request≈ 580 µs≈ 730–740 µs (+0.15 ms)≈ 1,140–1,330 µs (+0.55–0.75 ms)
Requests served when the CPU is the limit≈ 22,100 in 15 s≈ 19,800–20,000 (−10 %)≈ 11,600–13,400 (−40 %)
Mean latency under that load6.3 ms7.0 ms10.7–12.5 ms
Time added before the server listens—≈ 0+600–800 ms
Resident memory77 MB111 MB (+34 MB)137–139 MB (+60–62 MB)
Data sent per 1,000 requests—278 KB2,560 KB

Read it as a comparison, not as this SDK’s figures. The tracer measured was minimal (two spans per request, sent as JSON); @sypnia/telemetry/node does more work, and sends protobuf. OpenTelemetry can be made cheaper than in this test, with its protobuf exporter, sampling and fewer instrumentations. The startup difference matters most on serverless, where every cold start pays it.

Measured on this SDK

On 2026-11-16 we measured @sypnia/telemetry/node 0.1.0 itself, on the same laptop. The method is simpler than the one above, so compare the two tables with care: an http server in the same process as the load, whose handler makes two outgoing calls, 10 connections, 10,000 requests, with and without the SDK. CPU per request is the process’s CPU time divided by the requests.

MeasuredTarget
CPU per request≈ 1,080 µs with the SDK, ≈ 705 µs without (+0.37 ms)under 1 ms at the median, for a request with up to 20 spans
Time added at startup≈ 20 ms to import the package, ≈ 2 ms for initunder 50 ms added to a cold start
Package size16 kB gzippednone

The targets stay as the SDK’s commitments; a new measurement is published here with its date and its method. The SDK installs no module loader and patches no file as it loads, which is why its startup is short. It never delays a response on a long-running server: spans are exported in the background, in batches.

What holds by design, not by measurement:

  • A failure inside the SDK never reaches your code: every entry point is wrapped, and an export that fails is retried and then dropped, with one warning a minute at most.
  • When the project reaches a usage limit, the engine answers with Sypnia-Slow-Down and the SDK exports only requests that carry a failure until the date it names.

Next

  1. Install
  2. Check that it works
  3. What is traced without any code
  4. Database error details
  5. When a call has failed
  6. Requests that never finish
  7. Linking the browser to the server
  8. What it sends, and where
  9. init(options)
  10. Errors
  11. The functions you call
  12. reportError(error)
  13. identify(who)
  14. span(name, fn, attrs?)
  15. activeSpan() and setSpanAttributes(values)
  16. flush(timeoutMs?) and shutdown(timeoutMs?)
  17. wrapFetchHandler(handler)
  18. traceRequest(request, handle, options?)
  19. Graceful shutdown
  20. Serverless and other runtimes
  21. What it costs
  22. What was measured
  23. Measured on this SDK
  24. Next

    Search pages, sections and terms