npm package: @relayer-ws/residential-proxy-sdk
Description: Cloudflare Worker SDK for Residential Proxy
Author: relayer.ws
Latest version: 1.0.3

# Residential Proxy SDK for Cloudflare Workers

A TypeScript SDK that makes it easy to use residential proxy functionality from Cloudflare Workers. This SDK handles proxy configuration and automatic header setup for proxying requests through a residential proxy-enabled Lambda function.

## Features

- 🌐 **Residential IP Support**: Route requests through residential proxy networks
- 🚀 **Cloudflare Worker Compatible**: Built specifically for Cloudflare Workers
- 📦 **TypeScript First**: Full TypeScript support with comprehensive type definitions
- ⚡ **Easy to Use**: Simple API with convenient helper methods
- 🔧 **Flexible**: Support for all HTTP methods and custom headers
- 🔄 **Stable Mode**: Disables compression for stable proxy connections

## Installation

```bash
npm install @relayer-ws/residential-proxy-sdk
```

## Quick Start

### Using the Fetch API (Recommended)

The easiest way to use the SDK is with the fetch-like API:

```typescript
import { createResidentialFetch } from '@relayer-ws/residential-proxy-sdk';

// Create a residential proxy fetch function
const residentialFetch = createResidentialFetch({
  residentialProxyUrl: 'http://proxy.example.com:8080' // Optional
});

// Use it just like the native fetch API
const response = await residentialFetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer your-token',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ message: 'Hello World' })
});

const data = await response.json();
console.log(data);
```

### Using the Client Class

```typescript
import { ResidentialProxyClient } from '@relayer-ws/residential-proxy-sdk';

// Create a proxy client with default proxy URL (https://gw.relayer.ws/residential)
const proxy = new ResidentialProxyClient({});

// Or with custom proxy URL and residential proxy
const proxy = new ResidentialProxyClient({
  proxyUrl: 'https://your-lambda-url.amazonaws.com',
  residentialProxyUrl: 'http://proxy.example.com:8080'
});

// Make a proxied request
const response = await proxy.get('https://api.example.com/data', {
  'Authorization': 'Bearer your-token'
});

console.log(response.status); // 200
console.log(response.body);   // Response data
```

### Using Environment Variables

```typescript
import { createResidentialFetch } from '@relayer-ws/residential-proxy-sdk';

// In your Cloudflare Worker
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Create residential proxy fetch from environment variables
    const residentialFetch = createResidentialFetch({
      proxyUrl: env.RESIDENTIAL_PROXY_URL, // Optional - defaults to https://gw.relayer.ws/residential
      residentialProxyUrl: env.RESIDENTIAL_PROXY_PROXY_URL, // Optional
      timeout: env.RESIDENTIAL_PROXY_TIMEOUT ? parseInt(env.RESIDENTIAL_PROXY_TIMEOUT, 10) : undefined,
      userAgent: env.RESIDENTIAL_PROXY_USER_AGENT
    });
    
    // Use it just like fetch
    const response = await residentialFetch('https://api.example.com/webhook', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ message: 'Hello World' })
    });
    
    return response;
  }
};
```

## API Reference

### createResidentialFetch

Creates a residential proxy fetch function that works exactly like the native fetch API.

```typescript
function createResidentialFetch(config: ResidentialProxyConfig): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
```

**Parameters:**
- `config`: Configuration object (same as ResidentialProxyClient)

**Returns:** A fetch-like function that can be used exactly like the native fetch API.

**Example:**
```typescript
const residentialFetch = createResidentialFetch({
  residentialProxyUrl: 'http://proxy.example.com:8080'
});

// Use exactly like fetch
const response = await residentialFetch('https://api.example.com/data', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ data: 'value' })
});

const result = await response.json();
```

### ResidentialProxyClient

The main client class for making residential proxy requests.

#### Constructor

```typescript
new ResidentialProxyClient(config: ResidentialProxyConfig)
```

#### Configuration

```typescript
interface ResidentialProxyConfig {
  /** The URL of the residential proxy Lambda function (default: https://gw.relayer.ws/residential) */
  proxyUrl?: string;
  /** Optional residential proxy URL to use for the actual proxy connection */
  residentialProxyUrl?: string;
  /** Optional timeout for requests (default: 30000ms) */
  timeout?: number;
  /** Optional user agent string */
  userAgent?: string;
}
```

#### Methods

##### `request(options: ProxyRequestOptions): Promise<ProxyResponse>`

Make a custom proxied request.

```typescript
const response = await proxy.request({
  targetUrl: 'https://api.example.com',
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ data: 'value' }),
  timeout: 10000
});
```

##### `get(targetUrl: string, headers?: Record<string, string>): Promise<ProxyResponse>`

Make a GET request.

```typescript
const response = await proxy.get('https://api.example.com/users');
```

##### `post(targetUrl: string, body?: string | ArrayBuffer | ReadableStream, headers?: Record<string, string>): Promise<ProxyResponse>`

Make a POST request.

```typescript
const response = await proxy.post(
  'https://api.example.com/users',
  JSON.stringify({ name: 'John Doe' }),
  { 'Content-Type': 'application/json' }
);
```

##### `put(targetUrl: string, body?: string | ArrayBuffer | ReadableStream, headers?: Record<string, string>): Promise<ProxyResponse>`

Make a PUT request.

##### `delete(targetUrl: string, headers?: Record<string, string>): Promise<ProxyResponse>`

Make a DELETE request.

##### `patch(targetUrl: string, body?: string | ArrayBuffer | ReadableStream, headers?: Record<string, string>): Promise<ProxyResponse>`

Make a PATCH request.

##### `head(targetUrl: string, headers?: Record<string, string>): Promise<ProxyResponse>`

Make a HEAD request.

### Response Format

```typescript
interface ProxyResponse {
  /** HTTP status code */
  status: number;
  /** HTTP status text */
  statusText: string;
  /** Response headers */
  headers: Record<string, string>;
  /** Response body */
  body: string;
  /** Whether the response body is base64 encoded */
  isBase64Encoded: boolean;
}
```

## Cloudflare Worker Example

Here's a complete example of using the SDK in a Cloudflare Worker:

```typescript
import { createResidentialProxyClientFromEnv } from '@relayer-ws/residential-proxy-sdk';

interface Env {
  RESIDENTIAL_PROXY_URL?: string;  // Optional - defaults to https://gw.relayer.ws/residential
  RESIDENTIAL_PROXY_PROXY_URL?: string;  // Optional - residential proxy URL
  RESIDENTIAL_PROXY_TIMEOUT?: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    try {
      // Create proxy client from environment variables
      const proxy = createResidentialProxyClientFromEnv(env);
      
      // Parse the incoming request
      const url = new URL(request.url);
      const targetUrl = url.searchParams.get('target');
      
      if (!targetUrl) {
        return new Response('Missing target parameter', { status: 400 });
      }
      
      // Forward the request through the residential proxy
      const response = await proxy.request({
        targetUrl,
        method: request.method,
        headers: Object.fromEntries(request.headers.entries()),
        body: request.body
      });
      
      // Return the proxied response
      return new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers
      });
      
    } catch (error) {
      console.error('Proxy error:', error);
      return new Response('Internal Server Error', { status: 500 });
    }
  }
};
```

## Error Handling

The SDK provides comprehensive error handling:

```typescript
try {
  const response = await proxy.get('https://api.example.com');
} catch (error) {
  if (error.message.includes('timeout')) {
    console.error('Request timed out');
  } else if (error.message.includes('Invalid targetUrl')) {
    console.error('Invalid URL provided');
  } else {
    console.error('Request failed:', error.message);
  }
}
```

## Security Considerations

- **HTTPS Only**: Always use HTTPS URLs for both the proxy and target endpoints
- **Proxy Configuration**: Configure your residential proxy URLs securely
- **Header Filtering**: Sensitive headers like `X-Target-Url` and `X-Proxy-Url` are automatically handled by the proxy
- **Stable Mode**: The proxy automatically disables compression for stable connections

## Browser Testing

You can test the SDK functionality in your browser using the included test page:

```bash
# Start the test server
npm run test:browser

# Or from the root directory
yarn test:residential
```

This will open a browser test page at `http://localhost:3002` where you can:
- Configure the SDK settings
- Test different HTTP methods
- See simulated responses with residential IP addresses
- Experiment with web scraping and IP checking
- Test the API before implementing in your Cloudflare Worker

## License

MIT