@luminpdf/node-braze
v0.4.0
Published
A Node.js Braze SDK for event tracking via REST API
Readme
@luminpdf/node-braze
A Node.js Braze SDK for event tracking via the Braze REST API. This package provides a simple, type-safe interface for tracking events, attributes, and purchases to Braze from your server-side applications.
Features
- 🎯 Singleton Pattern: Ensures a single instance across your application
- 🔒 Type-Safe: Full TypeScript support with proper type definitions
- 📊 Event Tracking: Track events, attributes, and purchases to Braze
- 🚀 Batch Support: Track up to 75 events, attributes, or purchases per request
- 🔧 Flexible Configuration: Support for custom base URLs and development mode
- ⚡ Rate Limit Aware: Built-in validation for Braze API rate limits
Installation
npm install @luminpdf/node-brazeor
pnpm add @luminpdf/node-brazeor
yarn add @luminpdf/node-brazePrerequisites
- Braze REST API Key with
users.trackpermission - Node.js 18+ and TypeScript 4.5+
Usage
Initialize the Client
import { BrazeClient } from "@luminpdf/node-braze";
const brazeClient = BrazeClient.create({
apiKey: "your-braze-api-key",
baseUrl: "https://rest.iad-01.braze.com",
disableInDevelopment: false,
});Track a Single Event
await brazeClient.trackEvent({
external_id: "user-123",
eventName: "button_clicked",
properties: {
button_name: "signup",
page: "homepage",
},
});Track Events with Different User Identifiers
await brazeClient.trackEvent({
email: "[email protected]",
eventName: "page_view",
time: new Date().toISOString(),
properties: {
page: "/products",
referrer: "google.com",
},
});
await brazeClient.trackEvent({
user_alias: {
alias_name: "user-123",
alias_label: "user_id",
},
eventName: "purchase_completed",
properties: {
product_id: "prod-456",
amount: 99.99,
},
});Track Multiple Events (Batch)
await brazeClient.trackEvents([
{
external_id: "user-123",
eventName: "page_view",
properties: { page: "/home" },
},
{
external_id: "user-123",
eventName: "button_clicked",
properties: { button_id: "cta-signup" },
},
{
external_id: "user-456",
eventName: "product_viewed",
properties: { product_id: "prod-789" },
},
]);Track User Attributes
await brazeClient.trackAttribute({
external_id: "user-123",
attributes: {
first_name: "John",
last_name: "Doe",
email: "[email protected]",
custom_attribute: "value",
},
});Track Multiple Attributes (Batch)
await brazeClient.trackAttributes([
{
external_id: "user-123",
attributes: {
first_name: "John",
email: "[email protected]",
},
},
{
email: "[email protected]",
attributes: {
first_name: "Jane",
subscription_tier: "premium",
},
},
]);Track Purchases
await brazeClient.trackPurchase({
external_id: "user-123",
productId: "prod-456",
currency: "USD",
price: 99.99,
quantity: 2,
properties: {
category: "electronics",
discount_applied: true,
},
});Track Multiple Purchases (Batch)
await brazeClient.trackPurchases([
{
external_id: "user-123",
productId: "prod-456",
currency: "USD",
price: 99.99,
quantity: 1,
},
{
external_id: "user-123",
productId: "prod-789",
currency: "USD",
price: 49.99,
quantity: 2,
},
]);Advanced: Track Multiple Types in One Request
await brazeClient.trackUsers({
events: [
{
external_id: "user-123",
name: "page_view",
properties: { page: "/home" },
},
],
attributes: [
{
external_id: "user-123",
first_name: "John",
email: "[email protected]",
},
],
purchases: [
{
external_id: "user-123",
product_id: "prod-456",
currency: "USD",
price: 99.99,
},
],
});Get Instance After Initialization
import { BrazeClient } from "@luminpdf/node-braze";
const brazeClient = BrazeClient.getInstance();Check Configuration
const config = brazeClient.getConfig();
console.log(config.apiKey);
console.log(config.baseUrl);
const isConfigured = brazeClient.isClientConfigured();API Reference
BrazeClient.create(config: BrazeClientConfig): BrazeClient
Creates and returns a singleton instance of the BrazeClient.
Parameters:
config.apiKey(required): Your Braze REST API Keyconfig.baseUrl(optional): Braze API base URL (default: "https://rest.iad-01.braze.com")config.disableInDevelopment(optional): Disable tracking in development (default: false)
BrazeClient.getInstance(): BrazeClient
Returns the existing singleton instance. Throws an error if create() hasn't been called.
trackEvent(options: TrackEventOptions): Promise<TrackUsersResponse>
Tracks a single event to Braze.
Parameters:
options.external_id|user_alias|braze_id|email|phone(required): User identifieroptions.eventName(required): The name of the eventoptions.time(optional): ISO 8601 timestamp (default: current time)options.properties(optional): Event properties/attributes
trackEvents(events: TrackEventOptions[]): Promise<TrackUsersResponse>
Tracks multiple events in a single batch request (max 75 events).
Parameters:
events: Array of event options (max 75)
trackAttribute(options: TrackAttributeOptions): Promise<TrackUsersResponse>
Updates user attributes in Braze.
Parameters:
options.external_id|user_alias|braze_id|email|phone(required): User identifieroptions.attributes(required): Object containing user attributesoptions._update_existing_only(optional): Only update existing users (default: false)
trackAttributes(attributes: TrackAttributeOptions[]): Promise<TrackUsersResponse>
Updates multiple user attributes in a single batch request (max 75 attributes).
Parameters:
attributes: Array of attribute options (max 75)
trackPurchase(options: TrackPurchaseOptions): Promise<TrackUsersResponse>
Tracks a purchase event to Braze.
Parameters:
options.external_id|user_alias|braze_id|email|phone(required): User identifieroptions.productId(required): Product identifieroptions.currency(required): Currency code (e.g., "USD")options.price(required): Purchase priceoptions.quantity(optional): Quantity purchasedoptions.time(optional): ISO 8601 timestamp (default: current time)options.properties(optional): Purchase properties
trackPurchases(purchases: TrackPurchaseOptions[]): Promise<TrackUsersResponse>
Tracks multiple purchases in a single batch request (max 75 purchases).
Parameters:
purchases: Array of purchase options (max 75)
trackUsers(request: TrackUsersRequest): Promise<TrackUsersResponse>
Tracks a combination of events, attributes, and purchases in a single request.
Parameters:
request.attributes(optional): Array of attribute objects (max 75)request.events(optional): Array of event objects (max 75)request.purchases(optional): Array of purchase objects (max 75)
User Identifiers
You must provide one of the following user identifiers in each request:
external_id: Your internal user identifieruser_alias: Braze user alias withalias_nameandalias_labelbraze_id: Braze's internal user IDemail: User's email addressphone: User's phone number
Rate Limits
According to the Braze API documentation, the /users/track endpoint has:
- Base speed limit: 3,000 requests per three seconds
- Per request limits:
- Up to 75 event objects
- Up to 75 attribute objects
- Up to 75 purchase objects
- Up to 225 total user updates per request
The SDK automatically validates these limits and will throw an error if you exceed them.
Error Handling
The SDK throws errors if:
apiKeyis not provided- Client is used before initialization
- User identifier is missing
- Batch size exceeds 75 items
- Braze API calls fail
Always wrap tracking calls in try-catch blocks:
try {
await brazeClient.trackEvent({
external_id: "user-123",
eventName: "user_action",
properties: { action: "click" },
});
} catch (error) {
console.error("Failed to track event:", error);
}Response Format
All tracking methods return a TrackUsersResponse object:
{
message: "success",
attributes_processed?: number,
events_processed?: number,
purchases_processed?: number,
errors?: Array<{
type: string;
input: unknown;
message: string;
}>
}Development Mode
When disableInDevelopment is set to true, tracking methods will return early without making API calls when NODE_ENV is set to development or dev.
Braze API Regions
The default base URL is https://rest.iad-01.braze.com (US-01). For other regions, use:
- US-02:
https://rest.iad-02.braze.com - US-03:
https://rest.iad-03.braze.com - US-04:
https://rest.iad-04.braze.com - US-05:
https://rest.iad-05.braze.com - US-06:
https://rest.iad-06.braze.com - EU-01:
https://rest.fra-01.braze.eu - EU-02:
https://rest.fra-02.braze.eu
TypeScript Support
Full TypeScript support is included. Import types as needed:
import type {
BrazeClientConfig,
TrackEventOptions,
TrackAttributeOptions,
TrackPurchaseOptions,
TrackUsersRequest,
TrackUsersResponse,
} from "@luminpdf/node-braze";License
ISC
