Skip to main content

Core Types

Core TypeScript types and interfaces used throughout the Bloque SDK.

Configuration Types

BloqueSDKConfig

Public configuration object for the Bloque SDK. Used when initializing the SDK.
type BloqueSDKConfig = ConfigWithBaseUrl | ConfigWithMode;
You can provide either a custom baseUrl or a mode, but not both.

ConfigWithBaseUrl

Use a custom API endpoint:
baseUrl
string
required
Custom base URL for the SDK. When provided, mode cannot be specified.
origin
string
Origin identifier for the SDK. Used to scope requests to a specific origin within the Bloque platform.
  • Required for apiKey authentication
  • Optional for jwt authentication (resolved during authenticate())
platform
Platform
Platform where the SDK is executed. Determines the runtime environment and its capabilities.
  • node (default): backend runtime (Node.js, Bun, Deno). Supports API key authentication.
  • browser: web browser environment. Must use JWT authentication.
  • react-native: React Native environment. Must use JWT authentication.
  • bun: Bun runtime. Supports API key authentication.
  • deno: Deno runtime. Supports API key authentication.
auth
AuthStrategy
required
Authentication strategy used by the SDK.
  • { type: 'apiKey', apiKey: string }: for backend platforms
  • { type: 'jwt' }: for frontend platforms
tokenStorage
TokenStorage
JWT token storage strategy. See TokenStorage for details.
timeout
number
Default timeout for HTTP requests in milliseconds.Default: 30000 (30 seconds)
retry
RetryConfig
Retry configuration for failed requests. See RetryConfig for details.

ConfigWithMode

Use default production or sandbox endpoints:
mode
Mode
required
SDK operation mode:
  • 'production' (default): production environment with live data
  • 'sandbox': sandbox environment with mock data for testing
All other fields are the same as ConfigWithBaseUrl.

Examples

// Backend with API key (production)
const sdk = new SDK({
  mode: 'production',
  auth: { type: 'apiKey', apiKey: 'sk_...' },
  origin: 'my-app'
});

// Backend with custom endpoint
const sdk = new SDK({
  baseUrl: 'https://custom-api.example.com',
  auth: { type: 'apiKey', apiKey: 'sk_...' },
  origin: 'my-app'
});

// Browser with JWT
const sdk = new SDK({
  mode: 'production',
  platform: 'browser',
  auth: { type: 'jwt' },
  tokenStorage: customTokenStorage
});

// React Native with JWT
const sdk = new SDK({
  mode: 'sandbox',
  platform: 'react-native',
  auth: { type: 'jwt' },
  tokenStorage: secureStorage
});

Mode

SDK operation mode.
type Mode = 'production' | 'sandbox';
production
string
Production environment. Uses live endpoints and real data. This is the default mode.
sandbox
string
Sandbox environment. Uses isolated endpoints and mock data for development and testing.

Platform

Runtime platform where the SDK executes.
type Platform = 'node' | 'deno' | 'bun' | 'browser' | 'react-native';
node
string
Node.js runtime (backend)Typical use cases:
  • APIs
  • Backend services
  • Server-side workers
Supports private API keys.
deno
string
Deno runtime (backend)Typical use cases:
  • Serverless functions
  • Edge-like services
Supports private API keys.
bun
string
Bun runtime (backend)Typical use cases:
  • High-performance backend services
  • Local development servers
Supports private API keys.
browser
string
Browser runtime (frontend)Characteristics:
  • No access to private API keys
  • Authentication via JWT
  • Requests include credentials (credentials: 'include') to support httpOnly cookies
  • tokenStorage is optional
react-native
string
React Native runtime (mobile)Characteristics:
  • No access to private API keys
  • Authentication via JWT
  • tokenStorage is required to provide/store the JWT token

AuthStrategy

Authentication strategy for the SDK.
type AuthStrategy = 
  | { type: 'apiKey'; apiKey: string }
  | { type: 'jwt' };

API Key Authentication

type
'apiKey'
required
Authentication type
apiKey
string
required
Private API key for backend authentication (starts with sk_)
Usage:
{
  auth: { type: 'apiKey', apiKey: 'sk_live_...' }
}

JWT Authentication

type
'jwt'
required
Authentication type
Usage:
{
  auth: { type: 'jwt' }
}

TokenStorage

Interface for storing and retrieving JWT tokens in client-side platforms.
interface TokenStorage {
  get(): string | null;
  set(token: string): void;
  clear(): void;
}
get
() => string | null
required
Retrieves the currently stored JWT token.Returns the JWT token, or null if no token is stored.
set
(token: string) => void
required
Persists a JWT token.WARNING: If using localStorage/sessionStorage, this token will be accessible to any JavaScript code on the page, including malicious scripts.
clear
() => void
required
Clears the stored JWT token.

Security Considerations

localStorage / sessionStorage (INSECURE)
  • Vulnerable to XSS attacks - any malicious script can read the token
  • Should ONLY be used for development/testing or non-sensitive apps
  • NOT recommended for production applications handling sensitive data
httpOnly Cookies (RECOMMENDED)
  • Best security practice - not accessible to JavaScript
  • Protects against XSS attacks
  • Requires server-side cooperation to set cookies
Secure Storage (RECOMMENDED for mobile)
  • Use platform-specific secure storage (e.g., Keychain on iOS, Keystore on Android)
  • Libraries: @react-native-async-storage/async-storage, expo-secure-store

Examples

httpOnly Cookies (Recommended):
const cookieStorage: TokenStorage = {
  get: () => {
    // Token is automatically sent in httpOnly cookie
    // You may need to fetch from server or return null
    return null;
  },
  set: (token) => {
    // Send to server to set httpOnly cookie
    fetch('/api/auth/set-token', {
      method: 'POST',
      body: JSON.stringify({ token })
    });
  },
  clear: () => {
    // Call server to clear cookie
    fetch('/api/auth/logout', { method: 'POST' });
  }
};
localStorage (Development Only):
const localStorageTokenStorage: TokenStorage = {
  get: () => localStorage.getItem('bloque_token'),
  set: (token) => localStorage.setItem('bloque_token', token),
  clear: () => localStorage.removeItem('bloque_token')
};
React Native Secure Storage:
import * as SecureStore from 'expo-secure-store';

const secureStorage: TokenStorage = {
  get: () => SecureStore.getItemAsync('bloque_token'),
  set: (token) => SecureStore.setItemAsync('bloque_token', token),
  clear: () => SecureStore.deleteItemAsync('bloque_token')
};
In-Memory Storage (Most Secure):
let tokenCache: string | null = null;

const inMemoryStorage: TokenStorage = {
  get: () => tokenCache,
  set: (token) => { tokenCache = token; },
  clear: () => { tokenCache = null; }
};

RetryConfig

Configuration for automatic retry behavior.
interface RetryConfig {
  enabled?: boolean;
  maxRetries?: number;
  initialDelay?: number;
  maxDelay?: number;
}
enabled
boolean
Whether to enable automatic retries.Default: true
maxRetries
number
Maximum number of retry attempts.Default: 3
initialDelay
number
Initial delay in milliseconds before the first retry.Subsequent retries use exponential backoff: delay * (2 ^ attempt).Default: 1000 (1 second)
maxDelay
number
Maximum delay in milliseconds between retries.Prevents exponential backoff from growing too large.Default: 30000 (30 seconds)

Retry Scenarios

The SDK automatically retries for:
  • 429 (Too Many Requests) - respects Retry-After header
  • 503 (Service Unavailable)
  • Network errors (timeouts, connection failures)

Example

const sdk = new SDK({
  mode: 'production',
  auth: { type: 'apiKey', apiKey: 'sk_...' },
  retry: {
    enabled: true,
    maxRetries: 5,
    initialDelay: 2000,  // Start with 2 second delay
    maxDelay: 60000      // Cap at 60 seconds
  }
});

Request Types

RequestOptions

Options for making HTTP requests.
interface RequestOptions<U = unknown> {
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  path: string;
  body?: U;
  headers?: Record<string, string>;
  timeout?: number;
}
method
string
required
HTTP method
path
string
required
API endpoint path (e.g., /v1/accounts)
body
U
Request body (automatically serialized to JSON)
headers
Record<string, string>
Additional HTTP headers
timeout
number
Request timeout in milliseconds.If not specified, uses the default timeout from SDK config. Set to 0 to disable timeout for this specific request.Default: 30000 (30 seconds)
This interface is primarily for internal use. Most SDK methods accept optional timeout/headers as parameters.

Response Types

BloqueResponse

Standard API response wrapper.
interface BloqueResponse<T> {
  data?: T;
  error?: BloqueError;
}
data
T
Response data (present on success)
error
BloqueError
Error details (present on failure). See BloqueError.

BloqueError

Error response from the API.
interface BloqueError {
  message: string;
  code?: string;
  status?: number;
}
message
string
required
Human-readable error message
code
string
Error code (e.g., ‘INVALID_ALIAS’, ‘INSUFFICIENT_FUNDS’)
status
number
HTTP status code
This is the raw error format from the API. The SDK throws specialized error classes (see Error Classes) instead of returning this interface.

Type Usage Examples

Backend Configuration

import { SDK, type BloqueSDKConfig } from '@bloque/sdk';

const config: BloqueSDKConfig = {
  mode: 'production',
  platform: 'node',
  auth: {
    type: 'apiKey',
    apiKey: process.env.BLOQUE_API_KEY!
  },
  origin: 'my-app',
  timeout: 60000, // 60 seconds
  retry: {
    enabled: true,
    maxRetries: 3
  }
};

const sdk = new SDK(config);

Frontend Configuration

import { SDK, type BloqueSDKConfig, type TokenStorage } from '@bloque/sdk';

const tokenStorage: TokenStorage = {
  get: () => localStorage.getItem('token'),
  set: (token) => localStorage.setItem('token', token),
  clear: () => localStorage.removeItem('token')
};

const config: BloqueSDKConfig = {
  mode: 'sandbox',
  platform: 'browser',
  auth: { type: 'jwt' },
  tokenStorage
};

const sdk = new SDK(config);

Custom Request Options

// Most SDK methods accept optional timeout parameter
await sdk.accounts.card.create(params, {
  timeout: 10000 // 10 second timeout for this specific request
});

Build docs developers (and LLMs) love