# Install the Bugstack JavaScript SDK

The SDK reports uncaught server errors to Bugstack, which reproduces each one as a failing test in an isolated sandbox and sends a proven fix as a pull request. Setup for Express, Next.js route handlers and plain Node.js, with the full config reference. It runs on the server only: browser errors are not captured.

## Compatibility

**Node.js 18+** TypeScript 5+ (optional) Next.js 14+ Express 4.x / 5.x

Bugstack proves each fix by running your own tests with Vitest, Jest or Mocha in its verification sandbox: the reproduction test fails before the change and passes after it, with the rest of your suite green. [How the sandbox works](/docs/how-it-works#sandbox).

## Install

Install the SDK with your preferred package manager:

npm

```
npm install bugstack-sdk
```

pnpm

```
pnpm add bugstack-sdk
```

yarn

```
yarn add bugstack-sdk
```

## Initialize

Initialize once at startup with your API key and the Bugstack endpoint. Pass `endpoint` explicitly: the published SDK does not default to it yet. Reports are sent as soon as an error is captured, and retried up to 5 times if Bugstack cannot be reached.

## Express

Add `initBugStack` before your routes and `bugstackErrorHandler` after them. The handler reports the error and passes it on, so your own error handling still runs.

```
const { initBugStack, bugstackErrorHandler } = require('bugstack-sdk/express')

// After app creation:
app.use(initBugStack({
  apiKey: process.env.BUGSTACK_API_KEY,
  endpoint: process.env.BUGSTACK_ENDPOINT || 'https://dashboard.bugstack.ai/api/ingest/sdk',
}))

// ... your routes ...

// Before app.listen:
app.use(bugstackErrorHandler())
```

Express 4 does not route errors from `async` handlers to error middleware. Wrap them (Express 5 does this itself):

```
const { wrapExpressHandler } = require('bugstack-sdk/express')

// Express 4 does not pass async errors on by itself: wrap async handlers.
app.get('/users/:id', wrapExpressHandler(async (req, res) => {
  res.json(await getUser(req.params.id))
}))
```

## Next.js (App Router)

Initialize once in a module your route handlers import, then wrap each route handler with `withErrorCapture`. It reports the error and re-throws it. It wraps route handlers only: server actions, server components and middleware are not wrapped.

```
// lib/bugstack.ts
import { ErrorCaptureClient, withErrorCapture } from 'bugstack-sdk'

ErrorCaptureClient.init({
  apiKey: process.env.BUGSTACK_API_KEY!,
  endpoint: process.env.BUGSTACK_ENDPOINT ?? 'https://dashboard.bugstack.ai/api/ingest/sdk',
})

export { withErrorCapture }
```

```
// app/**/route.ts: wrap each route handler
import { withErrorCapture } from '@/lib/bugstack'

export const GET = withErrorCapture(async (request) => {
  // ...your handler, unchanged
  return Response.json({ ok: true })
})
```

## Plain Node.js

For a worker, a script or any other Node process:

```
const { initBugStack, installGlobalHandlers, captureError } = require('bugstack-sdk/generic')

initBugStack({
  apiKey: process.env.BUGSTACK_API_KEY,
  endpoint: process.env.BUGSTACK_ENDPOINT || 'https://dashboard.bugstack.ai/api/ingest/sdk',
})

// Report uncaught exceptions and unhandled promise rejections.
installGlobalHandlers()

// Or report an error you handle yourself:
async function runJob(job) {
  try {
    await processJob(job)
  } catch (err) {
    await captureError(err, { job: job.id })
  }
}
```

## Environment Variables

Variable

Description

Required

`BUGSTACK_API_KEY`

Your project API key from the dashboard

Yes

`BUGSTACK_ENDPOINT`

The endpoint, if you set it here instead of in code: `https://dashboard.bugstack.ai/api/ingest/sdk`

No

`BUGSTACK_PROJECT_ID`

Explicit project identifier

No

`NODE_ENV`

Used as the default `environment`, and turns `debug` off when it is `production`

No

## TypeScript Types

The SDK ships with TypeScript definitions. Key exported types:

```
import type {
  ErrorCaptureConfig,
  CapturedError,
  StackFrame,
  RouteOptions,
  RouteContext,
  ErrorReportPayload,
  SourceContext,
} from 'bugstack-sdk';
```

## Configuration Reference

Option

Type

Default

Description

`apiKey`

string

—

Required. Your project API key (starts `bsk_`).

`endpoint`

string

`BUGSTACK_ENDPOINT`, else a local development address

Where reports go. Set it to `https://dashboard.bugstack.ai/api/ingest/sdk`.

`projectId`

string

`BUGSTACK_PROJECT_ID`, else empty

Explicit project identifier.

`environment`

string

`NODE_ENV`, else `"development"`

Environment name sent with each report.

`enabled`

boolean

`true`

Master switch for error capture.

`captureRequestBody`

boolean

`false`

Include the request body (Next.js route handlers).

`captureQueryParams`

boolean

`true`

Include query parameters, with sensitive names redacted.

`captureHeaders`

boolean

`true`

Include request headers. Authorization, cookies and API-key headers are always redacted.

`maxBodySize`

number

`10000`

Bytes of request body kept before truncating.

`redactFields`

string\[\]

16 built-in names

Field names to redact, added to the built-in list: password, secret, token, apikey, api\_key, apiKey, authorization, auth, credential, private, credit\_card, creditcard, card\_number, cvv, ssn, social\_security.

`metadata`

Record<string, unknown>

`{}`

Extra data attached to every report.

`timeout`

number

`5000`

HTTP timeout in milliseconds for each report.

`deduplicationWindow`

number

`300000`

Milliseconds during which the same error is sent only once (5 minutes). Bugstack also folds repeats within 24 hours.

`debug`

boolean

`true` unless `NODE_ENV` is `production`

Log SDK activity to the console.

`shouldCapture`

(error, request) => boolean

—

Return `false` to skip an error.

`beforeSend`

(error: CapturedError) => CapturedError | null

—

Change a report before it is sent, or return `null` to drop it.

`dropChunkErrors`

boolean

`false`

Drop browser chunk-load errors entirely.

`autoFix`

boolean

`false`

Sent with each report. What Bugstack does with a fix is set by the repository's autonomy level in Bugstack, not by this flag.

## Next Steps

-   [JavaScript SDK Reference](/docs/sdk/javascript)
-   [Privacy & Data Handling](/docs/privacy)
-   [How Bugstack Works Under the Hood](/docs/how-it-works)
-   [JavaScript SDK Overview](/for/javascript)

## Get started

Sign up with GitHub and start the 14-day trial, or book a demo and we set it up with you. Once the SDK is in, an uncaught server error starts a fix: specialist agents work out the cause and write a small change, it arrives as a pull request that runs through your CI, and what happens next depends on the autonomy level you set. Connecting the repository also starts repository scanning.

[Get started](https://dashboard.bugstack.ai/login) [Book a demo](/demo)