npm package: @masmuch/error-tracker-sdk
Description: Universal error tracking SDK for JavaScript/TypeScript applications
Author: Masmuch
Latest version: 0.1.8

# @masmuch/error-tracker-sdk

[![npm version](https://badge.fury.io/js/@masmuch%2Ferror-tracker-sdk.svg)](https://www.npmjs.com/package/@masmuch/error-tracker-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://github.com/GooDevPro/error-tracker/actions/workflows/ci.yml/badge.svg)](https://github.com/GooDevPro/error-tracker/actions)
[![npm downloads](https://img.shields.io/npm/dm/@masmuch/error-tracker-sdk.svg)](https://www.npmjs.com/package/@masmuch/error-tracker-sdk)

Universal error tracking SDK for JavaScript/TypeScript applications. Works across **Node.js, Browser, Edge, and Serverless** environments.

## ✨ Why Choose This SDK?

- **🌍 Universal**: Works everywhere JavaScript runs (Node.js, Browser, Edge, Serverless)
- **🚀 Zero Dependencies**: Minimal footprint with only stacktrace-js as dependency
- **⚡ Smart Grouping**: Automatic error fingerprinting and deduplication
- **🔐 RBAC Built-in**: Multi-tenant with role-based access control
- **📊 Self-Hosted**: Deploy on your infrastructure, keep full data control
- **💰 Open Source**: Free and MIT licensed

## 🆚 Comparison with Other Solutions

| Feature      | Error Tracker | Sentry  | Bugsnag | Rollbar |
| ------------ | ------------- | ------- | ------- | ------- |
| Self-Hosted  | ✅            | ✅      | ❌      | ❌      |
| Open Source  | ✅            | ✅      | ❌      | ❌      |
| Free Tier    | Unlimited\*   | Limited | Limited | Limited |
| Multi-Tenant | ✅            | ❌      | ❌      | ❌      |
| Edge Support | ✅            | ✅      | ✅      | ✅      |
| Zero Config  | ✅            | ❌      | ❌      | ❌      |

\*When self-hosted

## 🗺️ Roadmap

### v0.2.0 (Q1 2025)

- [ ] Source maps support for better stack traces
- [ ] Performance monitoring integration
- [ ] Custom metadata schemas
- [ ] Webhooks for real-time notifications

### v0.3.0 (Q2 2025)

- [ ] Session replay functionality
- [ ] AI-powered error analysis
- [ ] Slack/Discord integrations
- [ ] Advanced filtering and search

### Future

- [ ] Mobile SDK (React Native, Flutter)
- [ ] APM (Application Performance Monitoring)
- [ ] Distributed tracing
- [ ] Log aggregation

## 📦 Installation

```bash
npm install @masmuch/error-tracker-sdk
# or
pnpm add @masmuch/error-tracker-sdk
# or
yarn add @masmuch/error-tracker-sdk
```

## 🧭 Dashboard Setup (Required)

Before initializing the SDK, create your organization, project, and token in the dashboard:

- Visit `https://error-tracker-web.vercel.app/`
- Sign in and create your company/organization
- Create a project within that organization
- Open the project → `Settings` → `API Keys`
- Generate an API Key (token) and copy it
- Use this API Key in `ErrorTracker.init({ apiKey: "..." })` or via the `ERROR_TRACKER_API_KEY` env var

## 🚀 Quick Start

```typescript
import { ErrorTracker } from "@masmuch/error-tracker-sdk";

// Initialize the SDK
ErrorTracker.init({
  apiKey: "your-dashboard-api-key",
  projectName: "my-project",
  environment: process.env.NODE_ENV,
  // apiUrl is optional - defaults to https://error-tracker-web.vercel.app
});

// Errors are now automatically captured!
```

## Manual Error Capture

```typescript
try {
  // Your code
} catch (error) {
  ErrorTracker.getInstance()?.captureError(error, {
    tags: { feature: "payment" },
    extra: { orderId: "12345" },
  });
}
```

## Configuration

```typescript
ErrorTracker.init({
  // Required
  apiKey: "your-api-key",

  // Optional
  apiUrl: "https://error-tracker-web.vercel.app", // Default: production instance
  projectName: "my-app",
  environment: "production",
  enabled: true,
  debug: false,

  // Auto-capture
  captureUnhandledRejections: true,
  captureUncaughtExceptions: true,

  // Performance
  enableBatching: true,
  batchSize: 10,
  batchInterval: 5000,
  maxEventsPerMinute: 100,

  // Sampling
  sampleRate: 1.0, // 0.0 to 1.0

  // Hooks
  beforeSend: (event) => {
    // Modify or filter events
    return event;
  },

  // Context
  tags: { version: "1.0.0" },
  user: {
    id: "user-123",
    email: "user@example.com",
  },
});
```

## Platform Support

Automatically detects and works on:

- ✅ Vercel
- ✅ AWS Lambda
- ✅ AWS EC2/ECS
- ✅ Cloudflare Workers
- ✅ Railway
- ✅ Render
- ✅ Heroku
- ✅ Node.js
- ✅ Browser

## Framework Integrations

### Next.js

```typescript
// app/layout.tsx or pages/_app.tsx
import { ErrorTracker } from "@masmuch/error-tracker-sdk";

ErrorTracker.init({
  apiKey: process.env.ERROR_TRACKER_API_KEY!, // Define in Vercel/environment
  environment: process.env.VERCEL_ENV,
});
```

### Express

```typescript
import { ErrorTracker } from "@masmuch/error-tracker-sdk";
import express from "express";

const app = express();

ErrorTracker.init({ apiKey: "your-key" });

// Error middleware
app.use((err, req, res, next) => {
  ErrorTracker.getInstance()?.captureError(err);
  res.status(500).send("Something broke!");
});
```

### AWS Lambda

```typescript
import { ErrorTracker } from "@masmuch/error-tracker-sdk";

ErrorTracker.init({ apiKey: process.env.ERROR_TRACKER_API_KEY! });

export const handler = async (event) => {
  try {
    // Your logic
  } catch (error) {
    ErrorTracker.getInstance()?.captureError(error);
    throw error;
  }
};
```

## 🤖 AI Assistant Integration (MCP)

Query and resolve errors directly from your terminal or IDE using AI assistants like **Claude**, **Warp**, and **Cursor**.

### What is MCP?

MCP (Model Context Protocol) allows AI assistants to interact with your Error Tracker data. Ask questions in natural language and get instant answers about your errors.

### Installation

```bash
npm install -g @masmuch/error-tracker-mcp
```

### Quick Setup

#### For Warp AI

Add to your Warp MCP configuration:

```json
{
  "error-tracker": {
    "command": "npx",
    "args": ["-y", "@masmuch/error-tracker-mcp"],
    "env": {
      "ERROR_TRACKER_API_KEY": "your_api_key_here"
    }
  }
}
```

> **Note:** `ERROR_TRACKER_API_URL` is optional. Defaults to `https://error-tracker-web.vercel.app`.
> Only specify it if you're using a self-hosted instance.

#### For Claude Desktop

Add to `~/.config/claude/config.json`:

```json
{
  "mcpServers": {
    "error-tracker": {
      "command": "npx",
      "args": ["-y", "@masmuch/error-tracker-mcp"],
      "env": {
        "ERROR_TRACKER_API_KEY": "your_api_key_here"
      }
    }
  }
}
```

> **Note:** `ERROR_TRACKER_API_URL` is optional and defaults to `https://error-tracker-web.vercel.app`.

### Example Queries

Once configured, ask your AI assistant:

- "List my error tracker projects"
- "Show me the critical errors from today"
- "Search for errors containing 'null pointer'"
- "Get error statistics for the last 7 days"
- "Mark error abc123 as resolved"
- "Find similar errors to abc123"

### Available Tools

The MCP provides 7 powerful tools:

1. **list_errors** - Filter and list errors with pagination
2. **get_error_details** - View complete error information including stack traces
3. **search_errors** - Full-text search across errors
4. **get_error_stats** - Analytics and statistics
5. **list_projects** - Show accessible projects
6. **resolve_error** - Update error status with audit logging
7. **get_similar_errors** - Find errors by fingerprint matching

### Learn More

- 📦 [MCP Package](https://www.npmjs.com/package/@masmuch/error-tracker-mcp)
- 📖 [MCP Documentation](https://github.com/masmuch/error-tracker/tree/main/apps/mcp-server)
- 🤖 [Model Context Protocol](https://modelcontextprotocol.io)

---

## Advanced Features

### Breadcrumbs

Track events leading up to an error:

```typescript
const tracker = ErrorTracker.getInstance();

tracker?.addBreadcrumb({
  category: "navigation",
  message: "User navigated to /checkout",
  level: "info",
});
```

### User Context

```typescript
tracker?.setUser({
  id: "user-123",
  email: "user@example.com",
  username: "johndoe",
});
```

### Custom Tags

```typescript
tracker?.setTags({
  feature: "checkout",
  version: "2.0.0",
});
```

### Extra Context

```typescript
tracker?.setExtra("orderId", "12345");
tracker?.setExtra("cartItems", ["item1", "item2"]);
```

## 📚 API Reference

### ErrorTracker.init(options)

Initializes the SDK with the provided configuration.

**Parameters:**

- `apiKey` (string, required): Your project API key
- `apiUrl` (string, optional): Custom tracker URL
- `projectName` (string, optional): Project identifier
- `environment` (string, optional): Environment (production, staging, etc.)
- `enabled` (boolean, optional): Enable/disable tracking (default: true)
- `debug` (boolean, optional): Enable debug logging (default: false)
- `captureUnhandledRejections` (boolean, optional): Auto-capture unhandled promise rejections (default: true)
- `captureUncaughtExceptions` (boolean, optional): Auto-capture uncaught exceptions (default: true)
- `enableBatching` (boolean, optional): Batch multiple errors (default: true)
- `batchSize` (number, optional): Events per batch (default: 10)
- `batchInterval` (number, optional): Batch interval in ms (default: 5000)
- `maxEventsPerMinute` (number, optional): Rate limit (default: 100)
- `sampleRate` (number, optional): Sampling rate 0.0-1.0 (default: 1.0)
- `beforeSend` (function, optional): Hook to modify/filter events
- `tags` (object, optional): Global tags for all events
- `user` (object, optional): User context

### ErrorTracker.getInstance()

Returns the singleton instance of ErrorTracker.

### captureError(error, context?)

Manually capture an error.

**Parameters:**

- `error` (Error | string): The error to capture
- `context` (object, optional): Additional context
  - `tags`: Object with string key-value pairs
  - `extra`: Additional metadata
  - `user`: User information

### addBreadcrumb(breadcrumb)

Add a breadcrumb to track events.

**Parameters:**

- `breadcrumb` (object):
  - `category` (string): Category of the event
  - `message` (string): Description
  - `level` (string): 'debug' | 'info' | 'warning' | 'error'
  - `data` (object, optional): Additional data

### setUser(user)

Set user context.

**Parameters:**

- `user` (object):
  - `id` (string)
  - `email` (string, optional)
  - `username` (string, optional)

### setTags(tags)

Set global tags.

**Parameters:**

- `tags` (object): Key-value pairs

### setExtra(key, value)

Set extra context.

**Parameters:**

- `key` (string): Context key
- `value` (any): Context value

## 🔧 Development

### Building from Source

```bash
# Clone the repository
git clone https://github.com/GooDevPro/error-tracker.git
cd error-tracker/packages/sdk

# Install dependencies
pnpm install

# Build
pnpm build

# Run tests
pnpm test

# Run tests in watch mode
pnpm test:watch
```

### Publishing to NPM

```bash
# Bump version
npm version patch|minor|major

# Build the package
pnpm build

# Publish to NPM
npm publish --access public
```

## 📝 Changelog

See [CHANGELOG.md](../../CHANGELOG.md) for release history.

## 👥 Contributing

Contributions are welcome! Please read [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.

## 🐛 Issues & Support

- **Bug Reports**: [GitHub Issues](https://github.com/GooDevPro/error-tracker/issues)
- **Documentation**: [Full Documentation](https://error-tracker-web.vercel.app)
- **Dashboard**: [Error Tracker Dashboard](https://error-tracker-web.vercel.app)
- **Questions**: [GitHub Discussions](https://github.com/GooDevPro/error-tracker/discussions)

## ✨ Features

- ✅ **Universal**: Works on any JavaScript runtime
- ✅ **Zero Config**: Auto-detects platform and environment
- ✅ **TypeScript**: Full type safety
- ✅ **Lightweight**: Minimal dependencies (only stacktrace-js)
- ✅ **Smart Batching**: Efficient error batching and rate limiting
- ✅ **Breadcrumbs**: Track user actions leading to errors
- ✅ **Context**: Rich error context with tags, user info, and metadata
- ✅ **Sampling**: Control data volume with sampling rates
- ✅ **Hooks**: beforeSend hook for filtering/modifying events

## 🛡️ Security

- API keys are transmitted securely via HTTPS
- No sensitive data is captured by default
- Use `beforeSend` hook to sanitize data before sending
- Supports custom API URLs for self-hosted instances

## 📊 Performance

- **Async**: Non-blocking error capture
- **Batching**: Reduces network overhead
- **Rate Limiting**: Prevents flooding
- **Lightweight**: < 50KB gzipped

## 📝 License

MIT License - see [LICENSE](../../LICENSE) for details

---

**Made with ❤️ by the Error Tracker Team**