# @critters/next

A lightweight error tracking library for Next.js applications that helps you understand and fix bugs faster. Critters automatically captures errors from both client and server-side code, providing clear, actionable insights without the complexity of traditional error monitoring tools.

## Features

- 🔒 Secure bug reporting with HMAC SHA-256 signatures
- 🌐 Works on both client and server-side
- 🚀 Easy integration with Next.js applications
- 🛡️ Rate limiting to prevent spam
- 📊 Structured error reports with metadata
- 📱 Browser information and device context
- 🔍 Network request capture
- 📝 Console log collection
- 👤 User interaction tracking

## Installation

```bash
pnpm add @critters/next
# or
npm install @critters/next
# or
yarn add @critters/next
```

## Setup

### 1. Initialize the Bug Tracker

Add the following code to your application's entry point (e.g., `app/layout.tsx` or `pages/_app.tsx`):

```tsx
import { startCritters } from "@critters/next";

// Initialize the bug tracker
startCritters({
  apiKey: process.env.NEXT_PUBLIC_BUG_TRACKER_API_KEY!,
  // Optional parameters:
  // endpoint: "https://your-custom-endpoint.com/api/bugs"
  // environment: process.env.NODE_ENV,
  // debug: process.env.NODE_ENV !== "production",
  // captureConsole: true,
  // captureNetworkRequests: true,
  // captureUserInteractions: true,
  // captureApplicationState: true,
});
```

The library will automatically fetch the necessary configuration (secretKey, projectId, etc.) from the server using your API key.

### 2. Set Up Your Project in Critters Dashboard

1. Create an account at [bugtrack.critters.dev](https://bugtrack.critters.dev)
2. Create a new project and get your API key
3. Add the API key to your environment variables as `NEXT_PUBLIC_BUG_TRACKER_API_KEY`

## Usage

### Manual Error Reporting

```tsx
import { catch_ } from "@critters/next";

try {
  // Your code that might throw an error
  throw new Error("Something went wrong!");
} catch (error) {
  catch_(error, { userId: "123", route: "/dashboard" });
}
```

### React Error Boundary

```tsx
import { ErrorBoundary } from "@critters/next";

function MyComponent() {
  return (
    <ErrorBoundary
      fallback={<div>Something went wrong</div>}
      captureProps={true} // Optional: include component props in the error report
    >
      <ComponentThatMightThrow />
    </ErrorBoundary>
  );
}
```

### Higher-Order Component for Error Boundaries

```tsx
import { withErrorBoundary } from "@critters/next";

const SafeComponent = withErrorBoundary(UnsafeComponent, {
  fallback: <div>Something went wrong</div>,
  captureProps: true, // Optional: include component props in the error report
  captureState: false, // Optional: include component state in the error report
});
```

### React Hook for Error Reporting

```tsx
import { useErrorReporting } from "@critters/next";

function MyComponent() {
  const { reportError } = useErrorReporting();

  const handleRiskyOperation = () => {
    try {
      // Risky operation
    } catch (error) {
      reportError(error, { context: "handleRiskyOperation" });
    }
  };

  return <button onClick={handleRiskyOperation}>Do Risky Thing</button>;
}
```

### API Route Error Handling

```tsx
import { withErrorReporting } from "@critters/next";

export default withErrorReporting(
  async function handler(req, res) {
    // Your API route logic
  },
  {
    captureRequest: true, // Optional: include request data in error report
  }
);
```

### Next.js App Router and Pages Router Integration

```tsx
import { withPageErrorReporting, withAppErrorReporting } from "@critters/next";

// For Pages Router
export default withPageErrorReporting()(MyPage);

// For App Router
export default withAppErrorReporting()(MyAppComponent);
```

## API Reference

### `initBugTracker(config)`

Initializes the bug tracker with configuration.

**Parameters:**

- `config`: Configuration object
  - `apiKey`: Public API key for identifying your application
  - `endpoint`: (Optional) URL of your custom endpoint (defaults to Critters API)
  - `secretKey`: (Optional) Secret key for signing requests (automatically fetched if not provided)
  - `projectId`: (Optional) Project ID for grouping bugs (automatically fetched if not provided)
  - `environment`: (Optional) Environment name (e.g., 'development', 'production')
  - `enabled`: (Optional) Whether the bug tracker is enabled (default: `true`)
  - `debug`: (Optional) Whether to log debug information (default: `false`)
  - `captureConsole`: (Optional) Whether to capture console logs (default: `true`)
  - `captureNetworkRequests`: (Optional) Whether to capture network requests (default: `true`)
  - `captureUserInteractions`: (Optional) Whether to capture user interactions (default: `true`)
  - `captureApplicationState`: (Optional) Whether to capture application state (default: `true`)
  - `onBeforeReport`: (Optional) Function called before sending a report
  - `onAfterReport`: (Optional) Function called after sending a report

### `catch_(error, metadata)`

Reports an error to the configured endpoint.

**Parameters:**

- `error`: Error object or any value that can be converted to a string
- `metadata`: (Optional) Additional information about the error

**Returns:**

- Promise that resolves to `{ success: boolean, message: string, reportId?: string, timestamp?: string }`

### `reportBug(error, metadata)` (Deprecated)

Legacy method for reporting errors. Use `catch_()` instead.

### `ErrorBoundary`

React component that catches errors in its children and reports them.

**Props:**

- `children`: React nodes to render
- `fallback`: (Optional) React node to render when an error occurs
- `onError`: (Optional) Function to call when an error is caught
- `captureProps`: (Optional) Whether to include component props in the error report
- `captureState`: (Optional) Whether to include component state in the error report

### `withErrorBoundary(Component, options)`

Higher-order component that wraps a component with an error boundary.

**Parameters:**

- `Component`: React component to wrap
- `options`: (Optional) Configuration object
  - `fallback`: React node to render when an error occurs
  - `onError`: Function to call when an error is caught
  - `captureProps`: Whether to include component props in the error report
  - `captureState`: Whether to include component state in the error report

**Returns:**

- Wrapped component with error boundary

### `useErrorReporting()`

React hook for reporting errors.

**Returns:**

- Object with `reportError` method for reporting errors

### `withErrorReporting(handler, options)`

Middleware for Next.js API routes that catches and reports errors.

**Parameters:**

- `handler`: Next.js API route handler
- `options`: (Optional) Configuration object
  - `captureRequest`: Whether to include request data in the error report
  - `captureResponse`: Whether to include response data in the error report
  - `onError`: Function to call when an error is caught

**Returns:**

- Wrapped handler with error reporting

### `withPageErrorReporting(options)`

Higher-order component for Next.js Pages that catches and reports errors.

**Parameters:**

- `options`: (Optional) Configuration object
  - `captureProps`: Whether to include page props in the error report
  - `captureInitialProps`: Whether to include getInitialProps data in the error report
  - `onError`: Function to call when an error is caught

**Returns:**

- Function that takes a Page component and returns a wrapped component with error reporting

### `withAppErrorReporting(options)`

Higher-order component for Next.js App Router components that catches and reports errors.

**Parameters:**

- `options`: (Optional) Configuration object
  - `captureParams`: Whether to include route params in the error report
  - `captureSearchParams`: Whether to include search params in the error report
  - `onError`: Function to call when an error is caught

**Returns:**

- Function that takes an App component and returns a wrapped component with error reporting

## Security Considerations

- The API key is used to fetch the necessary configuration from the server.
- The secretKey is never exposed to the client and is securely stored in the database.
- HMAC SHA-256 signatures verify the authenticity of error reports.
- Rate limiting prevents abuse of the reporting endpoint.
- Sensitive data is automatically sanitized from error reports.

## Contributing

### Commit Message Convention

We use [Conventional Commits](https://www.conventionalcommits.org/) for automated versioning and changelog generation. Please follow these conventions for your commit messages:

- `feat`: A new feature (minor version bump)
- `fix`: A bug fix (patch version bump)
- `docs`: Documentation changes
- `style`: Changes that don't affect the code's meaning
- `refactor`: Code changes that neither fix bugs nor add features
- `perf`: Performance improvements
- `test`: Adding or updating tests
- `build`: Changes to the build process or dependencies
- `ci`: Changes to CI configuration

**For breaking changes**, use one of these formats:

```
feat!: introduce a breaking change

# OR

feat: introduce a new feature

BREAKING CHANGE: description of the breaking change
```

Breaking changes will trigger a major version bump.

## License

MIT
