> ## Documentation Index
> Fetch the complete documentation index at: https://docs.steadwing.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK

> Install the Steadwing Node SDK to auto-capture exceptions, error logs, and HTTP breadcrumbs from your Node.js applications and send them to Steadwing for AI-powered root cause analysis.

## What is the Steadwing Node SDK?

The Steadwing Node SDK auto-captures exceptions, error logs, and HTTP breadcrumbs from your Node.js applications and sends them to Steadwing for root cause analysis. Add two lines of code and Steadwing starts monitoring your application no manual instrumentation required.

<CardGroup cols={2}>
  <Card title="Auto-Capture" icon="bolt">
    Unhandled exceptions, rejections, and error logs captured automatically
  </Card>

  <Card title="HTTP Breadcrumbs" icon="globe">
    Outgoing HTTP/HTTPS requests recorded with method, URL, status, and duration
  </Card>

  <Card title="Express & Fastify" icon="server">
    Route error capture with full request context
  </Card>

  <Card title="Data Scrubbing" icon="shield">
    Sensitive fields (passwords, tokens, API keys) redacted before sending
  </Card>
</CardGroup>

## Installation

```bash theme={null}
npm install @steadwing/node
```

Requires Node.js 18+. View on [npm](https://www.npmjs.com/package/@steadwing/node) or browse the [source on GitHub](https://github.com/steadwing/steadwing-node).

## Quick Start

Get your API key from [app.steadwing.com/organization](https://app.steadwing.com/organization), then initialize the SDK:

```javascript theme={null}
const steadwing = require("@steadwing/node");

steadwing.init({
    apiKey: "st_your_api_key"
});
```

That's it. The SDK automatically:

* Captures unhandled exceptions (`uncaughtException`)
* Captures unhandled promise rejections (`unhandledRejection`)
* Captures `console.error()`, winston, and pino error-level logs
* Records outgoing HTTP/HTTPS requests as breadcrumbs
* Sends heartbeats every 60 seconds

## Configuration

```javascript theme={null}
steadwing.init({
    apiKey: "st_...",          // Required: your API key
    service: "my-service",    // Optional: defaults to "default"
    env: "PROD",              // Optional: defaults to "PROD"
    enabled: true,            // Optional: set false to disable
});
```

<Note>
  Only events sent with `env="PROD"` are considered for auto-monitoring. Events from other environments are received but will not trigger automated RCA.
</Note>

## Manual Capture

For cases where you want to explicitly report errors or messages:

<Tabs>
  <Tab title="Capture Exception">
    ```javascript theme={null}
    const steadwing = require("@steadwing/node");

    // Capture a specific exception
    try {
        riskyOperation();
    } catch (err) {
        steadwing.captureException(err);
    }
    ```
  </Tab>

  <Tab title="Capture Message">
    ```javascript theme={null}
    const steadwing = require("@steadwing/node");

    steadwing.captureMessage("Deployment completed", "info");
    ```
  </Tab>
</Tabs>

## What Gets Captured

### Exceptions

| Data            | Description                                             |
| --------------- | ------------------------------------------------------- |
| Stack trace     | Full V8 stack trace with file, line, and column         |
| Exception chain | `Error.cause` chain included                            |
| Breadcrumbs     | Last 100 events leading up to the error                 |
| Request context | Method, path, headers (when using framework middleware) |

### Logs

* `console.error()` sent as events
* Winston error/crit/emerg-level logs sent as events
* Pino error/fatal-level logs sent as events
* All log levels recorded as breadcrumbs for context

### HTTP Breadcrumbs

Every outgoing HTTP/HTTPS request is recorded with:

* Method and URL
* Response status code
* Request duration
* Rolling buffer of last 100 entries

## Data Scrubbing

Sensitive data is automatically scrubbed before leaving your application. Keys matching the following patterns (case-insensitive) have their values replaced with `[REDACTED]`:

```
password, passwd, secret, api_key, apikey, token, auth,
authorization, cookie, csrf, session, credit_card, ssn
```

## Framework Support

| Framework   | What's Captured                                                |
| ----------- | -------------------------------------------------------------- |
| **Express** | Route errors with full request context (method, path, headers) |
| **Fastify** | Route errors with request context via onError hook             |
| **winston** | Error-level log capture (auto-detected)                        |
| **pino**    | Error-level log capture (auto-detected)                        |

### Express

Add the error handler as your last middleware:

```javascript theme={null}
const steadwing = require("@steadwing/node");
const express = require("express");

steadwing.init({ apiKey: "st_..." });

const app = express();

app.get("/", (req, res) => res.send("ok"));
app.get("/fail", (req, res, next) => next(new Error("DB timeout")));

// Add as the last middleware
app.use(steadwing.expressErrorHandler());

app.listen(3000);
```

### Fastify

Register the plugin on your Fastify instance:

```javascript theme={null}
const steadwing = require("@steadwing/node");
const fastify = require("fastify");

steadwing.init({ apiKey: "st_..." });

const app = fastify();
app.register(steadwing.fastifyErrorHandler());

app.listen({ port: 3000 });
```

Winston and pino are captured automatically when installed, no extra code needed.

## TypeScript

Full TypeScript support with exported types:

```typescript theme={null}
import { init, captureException, expressErrorHandler } from "@steadwing/node";
import type { SteadwingConfig } from "@steadwing/node";

const config: SteadwingConfig = {
    apiKey: "st_...",
    service: "my-service",
};

init(config);
```

## FAQs

<AccordionGroup>
  <Accordion title="Do I need to change my code?">
    No. After calling `steadwing.init()`, the SDK hooks into Node's exception handling, console, and HTTP modules automatically. For Express/Fastify request context, add one line of middleware.
  </Accordion>

  <Accordion title="What's the performance impact?">
    Minimal. Events are batched and sent every 5 seconds in a non-blocking flush. Breadcrumbs are stored in a fixed-size buffer. Timers use `unref()` so the SDK never keeps your process alive.
  </Accordion>

  <Accordion title="Can I disable it in development?">
    Yes. Pass `enabled: false` to `steadwing.init()` and the SDK becomes a no-op, no patches are installed and no events are sent.
  </Accordion>

  <Accordion title="How does it work with existing error tracking (Sentry, etc.)?">
    The SDK coexists with other error trackers. It listens on `process.on('uncaughtException')` and patches `console.error` without removing existing listeners or handlers.
  </Accordion>

  <Accordion title="Is my data secure?">
    Sensitive fields are scrubbed before transmission. Data is sent over HTTPS to Steadwing's backend. See the Data Scrubbing section for details on what's redacted.
  </Accordion>
</AccordionGroup>

Need help? Contact us at [hello@steadwing.com](mailto:hello@steadwing.com)
