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

# Node.js SDK overview and setup

> Install and configure the official AvraAPI Node.js SDK for a secure server-side integration.

The AvraAPI Node.js SDK is the recommended integration path for Node.js and
TypeScript backends. It authenticates each request with your Project Client ID,
Client Secret, and selected environment, then returns JSON as an `ApiResponse`
or generated media as a `BinaryResponse`.

<Warning>
  This SDK is for trusted server-side code only. Never put a Project Client
  Secret in browser JavaScript, a mobile app, a public repository, a frontend
  environment variable, or a client-facing response.
</Warning>

## Requirements

| Requirement | Supported value |
| - | - |
| Node.js | Node.js 18 or later |
| Package manager | npm or another package manager that installs npm packages |
| Package | `@avraapi/node-sdk` |
| Module systems | ESM `import` and CommonJS `require()` |
| Credentials | A Project Client ID and Client Secret from an AvraAPI project |

The current published Node.js SDK release is **1.2.0**. It includes Currency,
Security, Location, SMS, Utilities, and the server-only Universal Payment
Gateway lifecycle.

## Install the SDK

Install the package in your backend application:

```bash theme={null}
npm install @avraapi/node-sdk
```

Use an ESM import in an ESM project:

```ts title="ESM import" theme={null}
import { ApixClient } from '@avraapi/node-sdk';
```

The package also supports CommonJS. Use `require()` from a `.cjs` file or a
project configured for CommonJS:

```js title="CommonJS import" theme={null}
const { ApixClient } = require('@avraapi/node-sdk');
```

Both forms load the same public package contract. TypeScript declarations are
included with the package.

## Configure project credentials

Create an AvraAPI project, enable the services your backend needs, then store
its credentials in the server environment. The SDK reads these names:

```ini title="Server environment configuration" theme={null}
APIX_PROJECT_KEY=your_project_client_id
APIX_API_SECRET=your_project_client_secret
APIX_ENV=development
```

`APIX_PROJECT_KEY` is the Project Client ID. `APIX_API_SECRET` is its matching
Client Secret and must remain private. The SDK reads `process.env`; it does not
load a `.env` file itself. Use your framework, deployment platform, or an
environment loader to populate `process.env` before creating the client.

### Optional configuration

| Setting | Purpose | Default |
| - | - | - |
| `APIX_ENV` | Selects the project environment. `development` becomes `dev`; `production` becomes `prod`. | `dev` |
| `APIX_BASE_URL` | Overrides the AvraAPI base URL for an approved non-production environment. | `https://avraapi.com/api/v1` |
| `APIX_TIMEOUT` | Sets the full HTTP request timeout in milliseconds. | `30000` |

Keep the default base URL for production. Explicit values passed to
`ApixClient` override environment values.

## Create and reuse the client

Create one client after application configuration is available, then reuse it
through your server's dependency container, module singleton, or service
layer. Its service accessors are lazy: a service is created only when your
application first uses it.

```ts title="Environment-based setup" theme={null}
import { ApixClient } from '@avraapi/node-sdk';

// AvraAPI SDK call: reads APIX_PROJECT_KEY, APIX_API_SECRET, and APIX_ENV.
export const avraapi = new ApixClient();
```

For an application that resolves configuration itself, pass the values
explicitly:

```ts title="Explicit trusted-backend setup" theme={null}
import { ApixClient } from '@avraapi/node-sdk';

// AvraAPI SDK call. Keep these values in server-only configuration.
export const avraapi = new ApixClient({
  projectKey: process.env.APIX_PROJECT_KEY,
  apiSecret: process.env.APIX_API_SECRET,
  env: 'development',
  timeout: 30_000,
});
```

The Client ID and Client Secret are required. If either cannot be resolved, the
constructor throws before an API request is sent. The SDK also rejects a
browser-like runtime before it can use the Client Secret.

## Use Privacy Mode for one provider request

All provider services support `withPrivacyMode()`. Call it immediately before
the one provider operation that needs the AvraAPI privacy guarantee:

```ts title="Enable Privacy Mode for the next request" theme={null}
// AvraAPI SDK call. The next Security request carries X-Privacy-Mode: 1.
const response = await avraapi.security()
  .withPrivacyMode()
  .checkBurnerEmail({ email: 'customer@example.com' });
```

The SDK clears Privacy Mode after that request. It preserves normal routing,
billing, and usage tracking while applying the platform privacy guarantee to
request and response payload storage; it does not make a request anonymous.
Use it for provider-service calls only: `client.call()` does not expose this
fluent control.

<Note>
  `lookupIp({ ip, privacyMode: true })` and the Utility methods'
  `privacyMode: true` inputs remain supported. They send the same
  `X-Privacy-Mode: 1` header. Prefer `withPrivacyMode()` when a consistent
  next-request style is clearer.
</Note>

## Read a JSON response

Most provider operations return a Promise for an `ApiResponse`. The operation
result is in `data`; `requestId` is the safest value to retain in server logs or
support records when tracing a request.

```ts title="Read a typed JSON result" theme={null}
// AvraAPI SDK call.
const response = await avraapi.location().lookupIp({ ip: '203.0.113.10' });

// Your application code.
const country = response.data.country;
const timezone = response.data.timezone;
const requestId = response.requestId;
```

| `ApiResponse` property or helper | Use it for |
| - | - |
| `data` | The operation-specific result fields. |
| `meta` | Optional response metadata. |
| `requestId` | Support and troubleshooting correlation. |
| `httpStatus` | The successful HTTP status. |
| `get()` and `has()` | Safely reading nested values with dot notation. |
| `toJson()` | A formatted JSON representation for approved backend diagnostics. |

Do not return raw provider data or internal metadata directly to a browser.

## Handle generated files and images

Utilities return a `BinaryResponse` for PNG, SVG, and binary PDF output. It
contains a Node.js `Buffer`, content type, size, HTTP status, and nullable
request ID. QR and PDF operations configured for Base64 return `ApiResponse`
instead; barcode output is always binary media.

```ts title="Save a generated QR image" theme={null}
import { BinaryResponse } from '@avraapi/node-sdk';

// AvraAPI SDK call. PNG is the default QR output format.
const response = await avraapi.utilities().generateQr({
  data: 'https://example.com',
});

// Your application code.
if (response instanceof BinaryResponse) {
  await response.saveAs('./generated/qr-code.png');
}
```

Use `getBuffer()` when streaming media from your server, `toDataUri()` only for
an approved server-rendered use, and `isPdf()`, `isPng()`, or `isSvg()` before
choosing a media-specific workflow.

## Handle errors safely

Non-success AvraAPI responses reject with typed errors. Catch a specific error
only where your application has a clear recovery path, then handle
`ApixError` as the common API fallback.

```ts title="Safe async error handling" theme={null}
import {
  ApixError,
  ApixNetworkError,
  ApixValidationError,
} from '@avraapi/node-sdk';

try {
  // AvraAPI SDK call.
  await avraapi.security().checkBurnerEmail({
    email: 'customer@example.com',
  });
} catch (error) {
  if (error instanceof ApixValidationError) {
    // Your application code: correct the submitted field values.
    console.error(error.validationErrors);
  } else if (error instanceof ApixNetworkError) {
    // Your application code: apply a controlled retry policy where appropriate.
    console.error('AvraAPI could not be reached.');
  } else if (error instanceof ApixError) {
    // Keep this ID in backend logs or support records only.
    console.error({
      code: error.errorCode,
      requestId: error.requestId,
      httpStatus: error.httpStatus,
    });
  } else {
    throw error;
  }
}
```

| Error | Typical reason | Recommended handling |
| - | - | - |
| `ApixAuthenticationError` | HTTP `401`: credentials, project state, or environment do not match. | Correct configuration; do not retry unchanged credentials. |
| `ApixInsufficientFundsError` | HTTP `402`: the project cannot cover a billable request. | Restore the project balance before retrying. |
| `ApixValidationError` | HTTP `422`: request data is invalid. | Read `validationErrors`, correct the input, and send a new request. |
| `ApixRateLimitError` | HTTP `429`: the configured request limit was reached. | Back off before retrying. |
| `ApixServiceUnavailableError` | HTTP `503`: the project or service is unavailable. | Retry only when your workflow permits it. |
| `ApixNetworkError` | No usable response reached the SDK. | Check connectivity and use a controlled retry policy. |

Never send a Client Secret, raw exception payload, provider diagnostic, or
payment completion context to a browser response.

## Universal Payment Gateway

The Node.js SDK includes the released server-only UPG surface through
`avraapi.payment()`. It provides typed availability, checkout creation,
callback verification, authoritative completion, reconciliation, gateway
services, and Payment Elements helpers. Your application still owns pending
orders, idempotency, callback routes, fulfilment, and final business decisions.

<Card title="Universal Payment Gateway documentation" icon="credit-card" href="/universal-payment-gateway/overview">
  Follow the canonical checkout lifecycle, Payment Elements, completion, and
  gateway-specific guides. Never use the Client Secret or a completion context
  in browser code.
</Card>

## Next steps

<CardGroup cols={2}>
  <Card title="REST API Reference" icon="server" href="/api-reference/overview">
    Review provider request and response contracts.
  </Card>

  <Card title="Universal Payment Gateway" icon="credit-card" href="/universal-payment-gateway/overview">
    Build a server-authoritative payment integration.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.