Midaz SDK for TypeScript

The Midaz SDK for TypeScript serves as an essential tool for building financial integrations with ease and confidence. It provides a developer-friendly, fully typed interface that wraps around Midaz’s financial services platform, allowing you to concentrate on your business logic instead and not on the code.

Designed for clarity and scalability, the SDK enables you to work with Organizations, Ledgers, Accounts, Transactions, and more, whether you are creating a simple workflow or managing complex operations.

At its core, the SDK is built on a layered, modular architecture that prioritizes performance, extensibility, and an excellent developer experience.

Why use the Midaz SDK for TypeScript?

  • Type-safe by design: Built with full TypeScript support and precise type definitions.
  • Builder pattern: Fluent, readable interfaces to help you construct complex objects with ease.
  • Robust error handling: Smart recovery strategies and clear error signals, so you stay in control.
  • Observability included: Tracing, metrics, and logs, ready out of the box.
  • Layered architecture: Clean separation between client, entities, API, and models. Organized, predictable, scalable.
  • Automatic retries: Handle transient hiccups with configurable retry policies.
  • Concurrency controls: Built-in tools to run tasks in parallel, without losing control of throughput.
  • Fast with caching: In-memory caching to boost performance where it counts.
  • Strict validation: Catch invalid input early with clear, actionable error messages.

Getting started


Prerequisite

  • The Midaz SDK for TypeScript requires TypeScript v5.8 or later.

Installing the SDK

To start using the Midaz SDK for TypeScript, you must install the dependencies using the following command:

npm install midaz-sdk
yarn add midaz-sdk

Once installed, follow the examples in the Quick Start Guide section to learn how to use the Midaz SDK for TypeScript.


Authentication


The Midaz SDK for TypeScript gives you flexibility when it comes to authentication. You can choose the method that fits your setup:

API key

You can use a simple authentication method by adding an API Key.

const client = createClient({
  apiKey: 'your-api-key',
  environment: 'sandbox',
});

Access Manager authentication

For integration with external identity providers using OAuth:

const client = createClient({
  accessManager: {
    enabled: true,
    address: 'https://auth.example.com',
    clientId: 'your-client-id',
    clientSecret: 'your-client-secret',
  },
  environment: 'sandbox',
});

The Access Manager handles token handling for you, such as acquisition, caching, and renewal, so you don’t have to worry about managing tokens manually.

👍

Access Manager plugin

We offer an Access Manager plugin that you can use. If you'd like to know more about it, contact us.


Quick start guide


In the following sections, you will find practical code examples to help you understand how to use the Midaz SDK for TypeScript.

Create a client

This is the first, and possibly most important, step. The client is your main entry point to the SDK. It handles authentication and gives you access to all entity services.

Example:

import { createClient } from 'midaz-sdk';

const client = createClient({
  apiKey: 'your-api-key',
  environment: 'sandbox', // Options: 'development', 'sandbox', 'production'
});

Create an Asset

The best way to create assets is with the Builder Pattern using createAssetBuilder.

Example:

import { createAssetBuilder } from 'midaz-sdk';

const assetInput = createAssetBuilder('US Dollar', 'USD')
  .withType('currency')
  .withMetadata({ precision: 2, symbol: '$' })
  .build();

const asset = await client.entities.assets.createAsset('org_123', 'ledger_456', assetInput);

In this code, you will add the required name and assetCode fields to the builder const assetInput = createAssetBuilder('US Dollar', 'USD'), then add any additional properties with with* methods.


Create an Account

The easiest way to create accounts is with the Builder Pattern using createAccountBuilder.

Example:

import { createAccountBuilder } from 'midaz-sdk';

const accountInput = createAccountBuilder('Savings Account', 'USD')
  .withType('savings')
  .withAlias('personal-savings')
  .build();

const account = await client.entities.accounts.createAccount('org_123', 'ledger_456', accountInput);

In this code, you will add the required name and assetCode fields to the builder const accountInput = createAccountBuilder('Savings Account', 'USD'), then add any additional properties with with* methods.


Create a Transaction

The easiest way to create accounts is with the Builder Pattern using createTransactionBuilder.

Example:

import { createTransactionBuilder } from 'midaz-sdk';

const transactionInput = createTransactionBuilder()
  .withCode('payment_001')
  .withOperations([
    {
      accountId: 'source_account_id',
      assetCode: 'USD',
      amount: 100 * 100, // $100.00
      type: 'debit',
    },
    {
      accountId: 'destination_account_id',
      assetCode: 'USD',
      amount: 100 * 100, // $100.00
      type: 'credit',
    },
  ])
  .withMetadata({ purpose: 'Monthly payment' })
  .build();

In this code, you will add all properties with with* methods.


Error recovery

Use enhanced error recovery for critical operations

import { withEnhancedRecovery } from 'midaz-sdk/util/error';

const result = await withEnhancedRecovery(
  () => client.entities.transactions.createTransaction('org_123', 'ledger_456', transactionInput),
  {
    maxRetries: 3,
    enableSmartRecovery: true,
  }
);

Clean up resources

client.close();

Using Access Manager for authentication

import { createClientConfigWithAccessManager, MidazClient } from 'midaz-sdk';

// Initialize the client with Access Manager authentication
const client = new MidazClient(
  createClientConfigWithAccessManager({
    address: 'https://auth.example.com', // Identity provider address
    clientId: 'your-client-id', // OAuth client ID
    clientSecret: 'your-client-secret', // OAuth client secret
    tokenEndpoint: '/oauth/token', // Optional, defaults to '/oauth/token'
    refreshThresholdSeconds: 300, // Optional, defaults to 300 (5 minutes)
  })
    .withEnvironment('sandbox')
    .withApiVersion('v1')
);

// The SDK will automatically handle token acquisition and renewal
// You can now use the client as normal
const organizations = await client.entities.organizations.listOrganizations();

// For environment-specific configurations with Access Manager
const sandboxClient = new MidazClient(
  createSandboxConfigWithAccessManager({
    address: 'https://auth.example.com',
    clientId: 'your-client-id',
    clientSecret: 'your-client-secret',
  })
);

// Clean up resources when done
client.close();


SDK architecture


The Midaz SDK uses a multi-layered service architecture to provide a clean, modular, and scalable developer experience. It is organized into three key layers, as shown in Figure 1, each serving a distinct purpose.

  • Client interface: This is the primary entry point for SDK users. It manages configurations such as API keys and environments, initializes services lazily, and exposes all available functionality in a unified and discoverable manner.
  • Entity services layer: This layer contains domain-specific services (e.g., Accounts, Assets, and Transactions) and offers consistent methods for operations such as create, get, update, delete, and list. Additionally, specialized operations are included based on each entity's specific needs.
  • Core services layer: These foundational utilities are used by all entity services. They handle HTTP requests, input validation, error processing, observability, configuration, and caching.
Figure 1. The layered architecture of the Midaz SDK for TypeScript.

Figure 1. The layered architecture of the Midaz SDK for TypeScript.


The architecture of the SDK emphasizes:

  • Consistency through shared patterns across services
  • Scalability via dependency injection and service factories
  • Reliability through enhanced error handling and typed responses
  • Testability with support for mocking, integration, and contract testing

🔍

Dive Deeper

For more information about the Architecture, refer to the following pages:


Builder pattern


The Midaz SDK for TypeScript employs a builder design pattern to help you assemble advanced objects in a straightforward, safe, and adaptable way. Instead of pre-defining a set of inputs, it provides a step-by-step, fluent, chainable interface that walks you through the entire process.

Builder functions in the SDK:

  • Assist you by informing you of the parameters in advance.
  • Let you modify optional fields using .with*() methods and chain them.
  • Aid in avoiding invalid states through a guiding structure.
  • Hide internal complexity, which leads to better readability.

Example

Here’s a quick example:

const assetInput = createAssetBuilder('USD Currency', 'USD')
  .withType('currency')
  .withMetadata({ precision: 2 })
  .build();

You can then pass this assetInput to the corresponding create method in the SDK.

🔍

Dive deeper

For more information about Builder Pattern, check the Builder Pattern in Midaz SDK page.


Working with entities


Each entity service concentrates on distinct aspects of the financial domain, such as accounts, assets, or transactions.

These services provide a reliable method for creating, retrieving, updating, and deleting data while allowing meaningful interactions with each type of entity.

Additionally, they offer specialized features designed for their particular use case, enabling you to handle financial data with greater confidence and efficiency.

EntityDescription
OrganizationsManage business units and organizational data
LedgersStructure and manage financial records
AssetsWork with assets such as currencies, commodities, and other value units
AccountsCreate, retrieve, update, and delete accounts within a Ledger
SegmentsOrganize portfolios for analytics and reporting
PortfoliosGroup accounts and assets into meaningful financial collections
BalancesRetrieve and calculate asset balances for accounts
Asset RatesHandle exchange rates between different asset types
TransactionsCreate and manage transactions that move assets between accounts
OperationsManage atomic debits and credits that make up a transaction

You can access each of these services through the SDK client. They follow a consistent structure, making it easier to build and maintain financial features.

🔍

Dive deeper

For more information about working with each Entity, check the Entities pages.


Using utilities


The SDK provides a set of utility modules to streamline common operations, whether you're optimizing performance, handling errors, managing configurations, or enhancing observability.

These tools are designed to work seamlessly with the rest of the SDK and help you build robust financial applications with less effort.

UtilityDescription
Account HelpersSimplifies common account-related logic and transformations
CacheEnables lightweight caching for better runtime performance
ConcurrencyHelps coordinate and limit concurrent tasks safely and efficiently
ConfigCentralized configuration setup and access
DataAssists with data formatting and pagination tasks
Error HandlingOffers recovery strategies and error processing mechanisms
HTTP ClientProvides a low-level HTTP interface for direct API calls
NetworkAdds high-level networking features like retries and backoff
ObservabilityCaptures traces, metrics, and logs to support monitoring and debugging
PaginationHandles paginated responses with predictable, consistent helpers
ValidationValidates input and output data to help maintain data integrity

🔍

Dive deeper

For more information about the Utilities, check the Utilities pages.


Error handling


The Midaz SDK for TypeScript helps you handle errors clearly and consistently. When an error occurs during an SDK operation, a structured error is thrown. This error includes key fields to help you understand and resolve the issue:

  • code: A short, consistent identifier for the error type
  • message: A human-readable description
  • details: (Optional) Additional context or metadata
  • status: The HTTP status code, when available

Here’s how you might handle an error:

try {
  await client.transactions.create(transaction);
} catch (err) {
  console.error(`Error (${err.code}): ${err.message}`);
  // Optionally: inspect err.details or err.status
}

Common error codes

CodeDescriptionHTTP Status
invalid_inputYour request is missing required data or has invalid values400
unauthorizedAuthentication failed or credentials are missing401
forbiddenYou're not allowed to perform this action403
not_foundThe resource you're trying to access doesn't exist404
conflictThe operation conflicts with an existing resource409
internal_errorSomething went wrong on our side500
service_unavailableTemporary outage—try again later503

Best practices

  • Validate input before calling SDK methods to avoid invalid_input
  • Double-check auth when facing unauthorized or forbidden
  • Retry on transient issues like internal_error or service_unavailable
  • Use details to surface helpful debug info in development logs

The SDK is built to keep errors predictable and actionable, so you can focus on building, not debugging.

🔍

Dive deeper

For more information about error handling, check the following pages:


CI/CD pipeline


We use GitHub Actions to keep things smooth, automated, and production-ready:

  • Runs tests across multiple Node.js versions
  • Enforces code quality with ESLint and Prettier
  • Keeps dependencies up to date with Dependabot
  • Handles releases automatically using semantic versioning
  • Generates changelogs for full transparency

Want to contribute?


If you're thinking about contributing to the Midaz SDK for TypeScript, start with our contributing guide on GitHub. It covers everything you need to know to get started.


License


This project is licensed under Apache 2.0. For details, check the License page.