# 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: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service). Status: at launch.  
Source: https://docs.sypnia.com/sdks/node/

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`](https://docs.sypnia.com/sdks/nextjs), 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**

```bash
npm install @sypnia/node
```

**pnpm**

```bash
pnpm add @sypnia/node
```

**yarn**

```bash
yarn add @sypnia/node
```

**bun**

```bash
bun add @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`

```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,
});
```

**Self-hosted**

`src/instrument.ts`

```ts
import { init } from '@sypnia/node';

init({
  project: process.env.SYPNIA_PROJECT_KEY,
  endpoint: 'https://sypnia.example.com',
  service: 'shop-api',
  environment: process.env.SYPNIA_ENVIRONMENT ?? 'production',
  release: process.env.SYPNIA_RELEASE,
});
```

`src/server.ts`

```ts
import './instrument';
import express from 'express';

const app = express();
app.post('/api/checkout', checkout);
app.listen(3000);
```

`.env`

```bash
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.

> **Note: The key is an ingest key**
>
> The server uses an ingest key (`spk_…`), like the browser. It can only send. Never give a server SDK an API token (`sps_…`): ingest refuses it.

## 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

| What                         | Covers                                                                                                                         | Becomes                                                                                          |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| Incoming requests            | Every 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 calls          | `fetch`, and `http.request` / `https.request` (so also axios, got and most SDKs).                                              | A span of kind `http`, named `POST /v1/payments`.                                                |
| Postgres queries             | The `pg` package.                                                                                                              | A span of kind `db`, named by operation and table: `SELECT carts`. Never the statement's values. |
| Supabase and PostgREST calls | Recognized among the outgoing calls by their path (`/rest/v1/…`).                                                              | A span of kind `db`: `SELECT orders`, `INSERT orders`, `CALL create_order`.                      |
| Errors                       | Listed under [Errors](#errors).                                                                                                | `server_error`                                                                                   |

Other database drivers (MySQL, MongoDB, Redis, Prisma's own engine) are **\[Planned]**. Until then wrap the call in [`span()`](#spanname-fn-attrs), or use their OpenTelemetry instrumentation with the [OTLP intake](https://docs.sypnia.com/sdks/opentelemetry).

**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:

| Header             | Read as                                                                                                                   |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `traceparent`      | The 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-session` | The 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](https://docs.sypnia.com/sdks/browser#calls-to-your-api-and-traces).

## `init(options)`

| Option                  | Type                           | Default                                                           | What it does                                                                                                                                                                                |
| ----------------------- | ------------------------------ | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `project`               | `string`                       | `process.env.SYPNIA_PROJECT_KEY`                                  | The ingest key, `spk_…`. Without it the SDK does nothing and prints one warning.                                                                                                            |
| `endpoint`              | `string`                       | `process.env.SYPNIA_ENDPOINT`, else `'https://ingest.sypnia.com'` | Where to send. A self-hosted engine's base URL.                                                                                                                                             |
| `service`               | `string`, up to 80 characters  | `process.env.SYPNIA_SERVICE`, else `'server'`                     | The name of this service in traces.                                                                                                                                                         |
| `environment`           | `string`, 1 to 40 characters   | `process.env.SYPNIA_ENVIRONMENT`, else `'production'`             | The environment. Use the same names as the frontend.                                                                                                                                        |
| `release`               | `string`, up to 40 characters  | `process.env.SYPNIA_RELEASE`, else none                           | The release. Use the short git commit.                                                                                                                                                      |
| `enabled`               | `boolean`                      | `true`                                                            | `false` turns the SDK into a no-op.                                                                                                                                                         |
| `debug`                 | `boolean`                      | `false`                                                           | Prints 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) => string` | the built-in rule                                                 | Your 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.outgoing`      | `boolean`                      | `true`                                                            | Spans for outgoing HTTP calls.                                                                                                                                                              |
| `capture.db`            | `boolean`                      | `true`                                                            | Spans for `pg`, and naming of Supabase and PostgREST calls.                                                                                                                                 |
| `capture.consoleErrors` | `boolean`                      | `true`                                                            | Reports `console.error` during a request as a failure.                                                                                                                                      |
| `capture.uncaught`      | `boolean`                      | `true`                                                            | Reports uncaught exceptions and unhandled rejections.                                                                                                                                       |
| `propagate`             | `boolean`                      | `true`                                                            | Adds `traceparent` to outgoing calls.                                                                                                                                                       |
| `slowRequestMs`         | `number`                       | `20000`                                                           | When a request still running is reported as partial. `0` turns it off.                                                                                                                      |
| `flushBudgetMs`         | `number`                       | `50`                                                              | The longest the SDK waits for a send at the end of a serverless invocation.                                                                                                                 |
| `beforeSend`            | `(event) => event \| null`     | none                                                              | Called 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](https://docs.sypnia.com/reference/event-schema).

## Errors

| Caught without code                                           | How it appears                                                                                                                                                                                                          |
| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| An exception nobody caught, or an unhandled rejection         | A 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 failure | A failure named `HTTP 500`, with the route.                                                                                                                                                                             |
| `console.error` while handling a request                      | A 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`

```ts
import { reportError } from '@sypnia/node';

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

**Fastify**

`src/server.ts`

```ts
import { reportError } from '@sypnia/node';

app.addHook('onError', async (request, reply, error) => {
  reportError(error);
});
```

**Koa**

`src/server.ts`

```ts
import { reportError } from '@sypnia/node';

app.on('error', (error) => reportError(error));
```

**Hono**

`src/server.ts`

```ts
import { reportError } from '@sypnia/node';

app.onError((error, c) => {
  reportError(error);
  return c.json({ error: 'internal_error' }, 500);
});
```

## 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`

```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](https://docs.sypnia.com/sdks/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`

```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](#serverless-and-other-runtimes).

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`

```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 runs                                                                                          | What to do                                                                                                   | Status           |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ---------------- |
| A long-running Node server, Node 20 or newer                                                           | `import './instrument'` first. Everything on this page.                                                      | **\[At launch]** |
| Next.js                                                                                                | [`@sypnia/next`](https://docs.sypnia.com/sdks/nextjs).                                                       | **\[At launch]** |
| Functions written as `(request: Request) => Response`: Vercel Functions, Supabase Edge Functions, Hono | `wrapFetchHandler`, below.                                                                                   | **\[At launch]** |
| AWS Lambda handlers that receive API Gateway or Function URL events                                    | An adapter is **\[Planned]**. Today: the [OTLP intake](https://docs.sypnia.com/sdks/opentelemetry).          | **\[Planned]**   |
| Bun, Deno and Cloudflare Workers                                                                       | `wrapFetchHandler` uses only web-standard APIs and `AsyncLocalStorage`. It is not tested on these at launch. | **\[Planned]**   |

`api/checkout.ts`

```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
