Docs

Node

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

Applies to EngineCloud At launch

View as Markdown
On this page
  1. Install
  2. Check that it works
  3. What is traced without any code
  4. When a call has failed
  5. Requests that never finish
  6. Linking the browser to the server
  7. init(options)
  8. Errors
  9. The functions you call
  10. reportError(error)
  11. identify(who)
  12. span(name, fn, attrs?)
  13. flush(timeoutMs?) and shutdown(timeoutMs?)
  14. wrapFetchHandler(handler)
  15. Graceful shutdown
  16. Serverless and other runtimes
  17. Overhead
  18. Next

This page is for whoever runs a Node server: an API, a backend for a web app, a server-rendered site. @sypnia/node is MIT-licensed 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/next, which includes this.

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/node

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/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 one server_request event with the method, the route, the status and its spans, and then sent 1 event (200).

What is traced without any code

WhatCoversBecomes
Incoming requestsEvery request to a server built on Node’s http or https module: Express, Fastify, Koa, NestJS, Hono on Node, plain http.One server_request with method, path, route, status and duration.
Outgoing HTTP callsfetch, and http.request / https.request (so also axios, got and most SDKs).A span of kind http, named POST /v1/payments.
Postgres queriesThe pg package.A span of kind db, named by operation and table: SELECT carts. Never the statement’s values.
Supabase and PostgREST callsRecognized among the outgoing calls by their path (/rest/v1/…).A span of kind db: SELECT orders, INSERT orders, CALL create_order.
ErrorsListed under Errors.server_error

Other database drivers (MySQL, MongoDB, Redis, Prisma’s own engine) are Planned. Until then wrap the call in span(), or use their OpenTelemetry instrumentation with the OTLP intake.

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 and response bodies, 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.

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 reported at that moment as a partial record: the spans that finished and the calls still in flight. If the request finishes, the full record replaces it. If the platform kills it, the partial record is what you have. 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’s spans join the browser’s trace. Without it, the server starts a new trace.
x-sypnia-sessionThe 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.

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

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://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 event and every send to the console.
ignoreRoutes(string | RegExp)[][]Incoming paths that are not traced, on top of the defaults above. A string matches the path and everything under it.
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.
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(event) => event | nullnoneCalled with each event before it is queued. Return null to drop it.

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

Errors

Caught without codeHow it appears
An exception nobody caught, or an unhandled rejectionA failure with its stack. The SDK reports it and does not change what Node does next.
A call that failed (see above)A failure named after the call, such as HTTP 400 or DB 23505. Its 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 requestA failure with the logged text, 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/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. 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/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. 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.

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

const total = await span('price cart', () => priceCart(cart), { 'cart.items': cart.items.length });

name has at most 120 characters. attrs values are strings of at most 256 characters, numbers or booleans.

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.

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

Graceful shutdown

Events wait in memory for up to 2 seconds before they are sent in a batch. When your process is asked to stop, send them first:

src/server.ts
import { shutdown } from '@sypnia/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 doStatus
A long-running Node server, Node 20 or newerimport './instrument' first. Everything on this page.At launch
Next.js@sypnia/next.At launch
Functions written as (request: Request) => Response: Vercel Functions, Supabase Edge Functions, HonowrapFetchHandler, below.At launch
AWS Lambda handlers that receive API Gateway or Function URL eventsAn adapter is Planned. Today: the OTLP intake.Planned
Bun, Deno and Cloudflare WorkerswrapFetchHandler uses only web-standard APIs and AsyncLocalStorage. It is not tested on these at launch.Planned
api/checkout.ts
import { init, wrapFetchHandler } from '@sypnia/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 sends its events 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.

Overhead

Budgets the SDK commits to:

  • It adds under 1 millisecond to a request, at the median, for a request with up to 20 spans.
  • It never delays a response on a long-running server: events are sent in the background, in batches.
  • A failure inside the SDK never reaches your code: every entry point is wrapped, and a send that fails is retried and then dropped, with one warning a minute at most.

Next

  • Next.js

    One setup for the client and the server.
  • OpenTelemetry

    For every backend that is not Node.
  • Traces

    What a trace is and how it connects.

Sections

Start hereWhat Sypnia is, how it works, what is open source and what is the paid cloud, and the two ways to get your first problem in plain words.ConceptsThe ten ideas Sypnia is made of, each defined precisely, from a project and its keys to problems, traces and alerts.SDKsHow your app sends data to Sypnia. One SDK for the browser, one for Node, one for Next.js, and the OpenTelemetry intake for every other backend.The agentHow Sypnia analyses a problem, what it writes, what it sends to a model and what it never does.MCP and skillsConnect your coding agent to Sypnia so it can ask what is failing in production, read what it needs to fix it, and set Sypnia up for you.API referenceThe Sypnia HTTP API: one API for the open-source engine and for Sypnia Cloud, with every endpoint, parameter, response and error.CLI referenceThe sypnia command: how to install it, the variables it reads, what its exit codes mean, and where each command is documented.Self-hostingWhat you run when you host the Sypnia engine yourself, what you need, what it costs, and what you do not get compared with Sypnia Cloud.How the engine is builtThe whole Sypnia engine on one page, from a click in your app to the sentence your coding agent reads, with the design rules and the code that holds them.Sypnia CloudHow the paid service works, from organizations and roles to plans, limits, billing, where your data lives, the GitHub App and support.Privacy and securityWhat Sypnia collects from your app and its users, what it never collects, how masking works, how to delete data, and how the service is protected.LicensingWhich licence covers each part of Sypnia, what you may do with it, how the name may be used, and the terms of a contribution.GuidesStep-by-step recipes for the common ways to use Sypnia, from apps made with AI builders and Next.js on Vercel to Supabase, source maps in CI, alert e-mails from your own engine, and moving from Sentry.ReferenceThe pages you look things up in, from the event schema and the glossary to what is planned, the changelog and the common questions.
↑↓ to move↵ to openEsc to close