npm package: @qblocktech/metricsjs
Description: Lightweight JavaScript monitoring library for browser and Next.js apps
Author: QBlockTech
Latest version: 1.0.6

# MetricsJs

A lightweight JavaScript monitoring library for browser and Next.js applications. Track errors and events with latency metrics using a simple, fire-and-forget API.

## Features

- 🚀 **Lightweight**: No external dependencies
- ⚡ **Fire-and-forget**: Non-blocking, asynchronous metric collection
- 🌐 **Universal**: Works in browsers and Node.js environments
- 📦 **ES Module**: Modern JavaScript module format
- 🎯 **Simple API**: Just 2 methods to track everything you need

## Installation

```bash
npm install @qblocktech/metricsjs
```

## Quick Start

```javascript
import { emitError, emitEvent } from '@qblocktech/metricsjs';

// Track errors
emitError('user-service', '/api/users', 'Database connection failed');

// Track events with latency
emitEvent('auth-service', '/api/login', 150); // 150ms response time
```

## Configuration

Set the `METRICS_COLLECTOR_API_KEY` environment variable to authenticate requests:

```bash
export METRICS_COLLECTOR_API_KEY=your-api-key-here
```

## API Reference

### Configuration

```javascript
import { configure } from '@qblocktech/metricsjs';

configure({
  endpoint: 'https://your-domain.com/collect', // Default: 'https://collect'
  timeout: 5000 // Request timeout in milliseconds
});
```

### Error Tracking

```javascript
emitError(service, endpoint, error_message)
```

**Parameters:**
- `service` (string): The service name where the error occurred
- `endpoint` (string): The endpoint where the error occurred
- `error_message` (string): The error message

**Examples:**
```javascript
// Database error
emitError('payment-service', '/api/payment', 'Payment gateway timeout');

// Authentication error
emitError('auth-service', '/api/login', 'Invalid credentials provided');
```

### Event Tracking

```javascript
emitEvent(service, endpoint, latency)
```

**Parameters:**
- `service` (string): The service name
- `endpoint` (string): The endpoint
- `latency` (number): The response time in milliseconds

**Examples:**
```javascript
// API response tracking
const start = Date.now();
await apiCall();
const latency = Date.now() - start;
emitEvent('user-service', '/api/users', latency);

// Database query tracking
emitEvent('payment-service', '/api/payments', 245);
```

## Data Format

All metrics are sent as POST requests to the configured endpoint with the following format:

```json
{
  "type": "error" | "event",
  "data": { /* metric-specific data */ },
  "ts": 1699999999999
}
```

### Error Data Structure
```json
{
  "type": "error",
  "data": {
    "service": "payment-service",
    "endpoint": "/api/payment",
    "error_message": "Payment gateway timeout"
  },
  "ts": 1699999999999
}
```

### Event Data Structure
```json
{
  "type": "event",
  "data": {
    "service": "user-service",
    "endpoint": "/api/users",
    "latency": 150,
    "timestamp": 1699999999999
  },
  "ts": 1699999999999
}
```

## Usage with Next.js

```javascript
// pages/_app.js or app/layout.js
import { configure, emitError } from '@qblocktech/metricsjs';

configure({
  endpoint: 'https://your-analytics-domain.com/collect'
});

// Global error boundary
export default function MyApp({ Component, pageProps }) {
  useEffect(() => {
    const handleError = (error) => {
      emitError('frontend', window.location.pathname, error.error.message);
    };
    
    window.addEventListener('error', handleError);
    return () => window.removeEventListener('error', handleError);
  }, []);

  return <Component {...pageProps} />;
}
```

## Usage in Browser

```html
<script type="module">
import { emitEvent, emitError } from 'https://unpkg.com/@qblocktech/metricsjs';

// Track page load time
window.addEventListener('load', () => {
  const loadTime = performance.timing.loadEventEnd - performance.timing.navigationStart;
  emitEvent('frontend', 'page_load', loadTime);
});
</script>
```

## TypeScript Support

The library includes TypeScript definitions:

```typescript
import { emitError, emitEvent, configure } from '@qblocktech/metricsjs';

// Track an API error
emitError('user-service', '/api/users', 'Database connection failed');

// Track API response time
emitEvent('auth-service', '/api/login', 245);
```

## Error Handling

MetricsJs follows a fire-and-forget pattern and will never throw errors or block your application. All network failures are silently ignored to ensure your application's performance is not affected.

## Browser Compatibility

- Modern browsers with fetch API support
- Node.js 14+ 
- Next.js (all versions)

## License

MIT