> ## Documentation Index
> Fetch the complete documentation index at: https://docs.straddle.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK for Straddle

> Install and configure the official Straddle Node.js SDK. Authenticate, make API calls, handle errors, and integrate ACH payments in JavaScript or TypeScript.

The Straddle Node.js SDK provides type-safe access to the Straddle API, with built-in TypeScript support and convenient methods for all API operations.

<Info>
  The SDK includes comprehensive TypeScript definitions and supports all modern JavaScript environments including Node.js, Deno, and Bun.
</Info>

## Installation

Install the SDK using npm:

```bash theme={null}
npm install @straddlecom/straddle
```

Or using yarn:

```bash theme={null}
yarn add @straddlecom/straddle
```

## Setup and Configuration

<Steps>
  <Step title="Import the SDK" icon="file-import">
    Import the appropriate client based on your needs:

    ```typescript theme={null}
    import Straddle from '@straddlecom/straddle';
    ```
  </Step>

  <Step title="Initialize the Client" icon="gear">
    Create a new instance of the Straddle client:

    ```typescript theme={null}
    const client = new Straddle({
        apiKey: process.env['STRADDLE_API_KEY'],
        environment: 'sandbox', // or 'production'
    });
    ```

    <Warning>
      Never hardcode your API key directly in your code. Use environment variables or a secure configuration
      management system.
    </Warning>
  </Step>
</Steps>

## Implementation Examples

<Tabs>
  <Tab title="Straddle Account Customers">
    For account customers (non-platform), the flow is simpler as the account context is inferred from the API key:

    ```typescript theme={null}
    import Straddle from '@straddlecom/straddle';

    async function accountFlow() {
        const client = new Straddle({
            apiKey: process.env['STRADDLE_API_KEY'],
            environment: 'sandbox'
        });

        // 1. Create a customer
        const customer_response = await client.customers.create({
            device: {
                ip_address: '192.168.0.1'
            },
            email: 'customer@example.com',
            name: 'Customer Name',
            phone: '+15555555555',
            type: 'individual'
        });
        const customer = customer_response.data;

        // 2. Link a bank account
        const paykey_response = await client.bridge.link.bankAccount({
            customer_id: customer.id,
            routing_number: '011000028',
            account_number: '000123456789',
            account_type: 'checking'
        });
        const paykey = paykey_response.data;

        // 3. Create a charge
        const charge = await client.charges.create({
            amount: 1,
            config: {
                balance_check: 'required'
            },
            consent_type: 'internet',
            currency: 'USD',
            description: 'Monthly subscription fee',
            device: {
                ip_address: '192.168.1.1'
            },
            external_id: 'external_id',
            paykey: paykey.paykey,
            payment_date: '2025-01-30'
        });
    }

    accountFlow().catch(console.error);
    ```
  </Tab>

  <Tab title="Embed Customers">
    This example demonstrates the complete flow for Embed customers:

    ```typescript theme={null}
    import Straddle from '@straddlecom/straddle';

    async function embedFlow() {
        const client = new Straddle({
            apiKey: process.env['STRADDLE_API_KEY'],
            environment: 'sandbox'
        });

        // 1. Create an organization
        const org_response = await client.embed.organizations.create({
            name: 'SDK Test Organization in Sandbox'
        });
        const organization = org_response.data;

        // 2. Create an account for the organization
        const account_response = await client.embed.accounts.create({
            organization_id: organization.id,
            account_type: 'business',
            business_profile: {
                name: 'Last SDK Test',
                website: 'straddle.com'
            },
            access_level: 'standard'
        });
        const account = account_response.data;

        // 3. Create a customer
        const customer_response = await client.customers.create({
            "Straddle-Account-Id": account.id,
            device: {
                ip_address: '192.168.0.1'
            },
            email: 'customer@example.com',
            name: 'Customer Name',
            phone: '+15555555555',
            type: 'individual'
        });
        const customer = customer_response.data;

        // 4. Link a bank account
        const paykey_response = await client.bridge.link.bankAccount({
            "Straddle-Account-Id": account.id,
            customer_id: customer.id,
            routing_number: '011000028',
            account_number: '000123456789',
            account_type: 'checking'
        });
        const paykey = paykey_response.data;

        // 5. Create a charge
        const charge = await client.charges.create({
            "Straddle-Account-Id": account.id,
            amount: 1,
            config: {
                balance_check: 'required'
            },
            consent_type: 'internet',
            currency: 'USD',
            description: 'Monthly subscription fee',
            device: {
                ip_address: '192.168.1.1'
            },
            external_id: 'external_id',
            paykey: paykey.paykey,
            payment_date: '2025-01-30'
        });
        console.log(charge.data);
    }

    embedFlow().catch(console.error);
    ```
  </Tab>
</Tabs>

## Key Features

<CardGroup cols={2}>
  <Card title="TypeScript Support" icon="shield-check">
    Complete TypeScript definitions for all request params and response fields, providing excellent IDE support.
  </Card>

  <Card title="Promise-Based" icon="bolt">
    Modern promise-based API with async/await support for clean, readable code.
  </Card>

  <Card title="Automatic Pagination" icon="list-tree">
    Built-in support for automatic pagination, making it easy to handle large result sets.
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Comprehensive error types and helpful error messages for better debugging and error recovery.
  </Card>
</CardGroup>

## Error Handling

The SDK provides specific exception types for different error cases:

<AccordionGroup>
  <Accordion icon="bug" title="Common Error Types">
    ```typescript theme={null}
    try {
        const charge = await client.charges.create({
            amount: 1000,
            currency: 'USD',
            // ... other required params
        });
    } catch (error) {
        if (error instanceof Straddle.APIError) {
            console.log(error.status);   // HTTP status code
            console.log(error.message);  // Error message
        }
    }
    ```

    Common error types include:

    * `BadRequestError` (400)
    * `UnprocessableEntityError` (422)
    * `AuthenticationError` (401)
    * `PermissionDeniedError` (403)
    * `NotFoundError` (404)
    * `RateLimitError` (429)
    * `InternalServerError` (>500)
  </Accordion>

  <Accordion icon="clock" title="Timeout Configuration">
    Configure request timeouts:

    ```typescript theme={null}
    // Simple timeout
    const client = new Straddle({
        timeout: 20 * 1000  // 20 seconds
    });

    // Per-request timeout
    await client.charges.create({
        // ... params
    }, {
        timeout: 5 * 1000  // 5 seconds
    });
    ```
  </Accordion>
</AccordionGroup>

## SDK Requirements

<CardGroup cols={2}>
  <Card title="Node Version" icon="node-js">
    Node.js 18 LTS or higher
  </Card>

  <Card title="TypeScript Version" icon="code">
    TypeScript >= 4.5
  </Card>
</CardGroup>

For more detailed information about the SDK structure and usage, refer to our [NPM Package](https://www.npmjs.com/package/@straddlecom/straddle).
