```yaml
product: AlterLab
title: Node.js SDK
category: sdk
comparison_context: "AlterLab is an alternative to Firecrawl, ScrapingBee, and Bright Data."
source_url: https://alterlab.io/docs/sdk/node
```

# Node.js SDK

The official Node.js/TypeScript SDK for AlterLab. Zero dependencies, fully typed, modern async API.

- **Package**: [alterlab on npm](https://www.npmjs.com/package/alterlab)
- **Requirements**: Node.js 18+
- **Features**: Full TypeScript, native fetch, ESM + CJS, zero dependencies

## Installation

```bash
npm install alterlab
```

## Quick Start

```typescript
import { AlterLab } from "alterlab";

const client = new AlterLab({ apiKey: "sk_live_..." });

const result = await client.scrape("https://example.com");

console.log(result.text); // Extracted text
console.log(result.json); // Structured JSON
console.log(result.billing.costDollars); // Cost in USD
console.log(result.billing.tierUsed); // Which tier succeeded
```

## Client Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | string | env var | Your AlterLab API key |
| `baseUrl` | string | alterlab.io | API base URL |
| `timeout` | number | 120000 | Request timeout in ms |
| `maxRetries` | number | 3 | Max retries on failure |
| `retryDelay` | number | 1000 | Initial retry delay in ms |

## Scraping Methods

### `client.scrape(url, options?)`

Main scraping method with full options:

```typescript
const result = await client.scrape("https://example.com", {
  mode: "auto",
  waitFor: "#content",
  screenshot: true,
  formats: ["text", "json", "markdown"],
  cache: true,
  cacheTtl: 3600,
  costControls: { maxTier: 3, prefer: "cost", failFast: true },
});
```

### `client.scrapeHtml(url)`
HTML-only mode (fastest, cheapest).

### `client.scrapeJs(url, options?)`
JavaScript rendering with Playwright.

### `client.scrapePdf(url)` / `client.scrapeOcr(url)`
Extract text from PDFs and images.

## Structured Extraction

### JSON Schema

```typescript
const result = await client.scrape("https://store.com/product/123", {
  extractionSchema: {
    type: "object",
    properties: {
      name: { type: "string" },
      price: { type: "number" },
      inStock: { type: "boolean" },
    },
  },
});
console.log(result.json);
```

### Pre-built Profiles

```typescript
const result = await client.scrape("https://store.com/product/123", {
  extractionProfile: "product", // product, article, job_posting, contact
});
```

### Natural Language

```typescript
const result = await client.scrape("https://news.example.com/article", {
  extractionPrompt:
    "Extract the article title, author, date, and main content",
});
```

## Cost Controls

```typescript
const result = await client.scrape("https://example.com", {
  costControls: {
    maxTier: 2,
    prefer: "cost",
    failFast: true,
    maxCostDollars: 0.001,
  },
});

// Estimate before scraping
const estimate = await client.estimateCost("https://linkedin.com");
console.log(`Estimated: $${estimate.estimatedCostDollars.toFixed(4)}`);
```

## Async Jobs

```typescript
const jobId = await client.scrapeAsync("https://example.com", {
  mode: "js",
});

// Poll manually
const status = await client.getJobStatus(jobId);

// Or wait for completion
const result = await client.waitForJob(jobId, {
  pollInterval: 2000,
  timeout: 300000,
});
```

## Error Handling

```typescript
import {
  AlterLab,
  AuthenticationError,
  InsufficientCreditsError,
  RateLimitError,
  ScrapeError,
  TimeoutError,
} from "alterlab";

try {
  const result = await client.scrape("https://example.com");
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.log("Invalid API key");
  } else if (error instanceof InsufficientCreditsError) {
    console.log(`Balance: $${error.balanceDollars}`);
  } else if (error instanceof RateLimitError) {
    console.log(`Retry after ${error.retryAfter}s`);
  }
}
```

| Exception | HTTP Code | Description |
|-----------|-----------|-------------|
| `AuthenticationError` | 401 | Invalid or missing API key |
| `InsufficientCreditsError` | 402 | Insufficient balance |
| `RateLimitError` | 429 | Too many requests |
| `ValidationError` | 400 | Invalid request parameters |
| `ScrapeError` | 422 | Scraping failed |
| `TimeoutError` | - | Request timed out |

## TypeScript Types

All types are exported:

```typescript
import {
  ScrapeResult,
  ScrapeOptions,
  BillingDetails,
  CostControls,
  UsageStats,
} from "alterlab";
```
