Node.js SDK

Learn how to integrate the Brevo API into your Node.js and browser applications.
View as Markdown

Overview

The Brevo Node.js SDK (@getbrevo/brevo) is a TypeScript-first client library for the Brevo API. It provides:

  • A unified BrevoClient with namespaced service clients
  • Full TypeScript types with IDE autocomplete
  • Promise-based async/await API
  • Automatic retries with exponential backoff
  • Custom fetch support for any runtime
  • Structured error handling with typed error classes

npm

Version 6.0 introduces breaking changes versus v5.x. v5.x remains supported and continues to receive wire-compatibility fixes — see the changelog for the list of changes and the README for migration steps.

Requirements

  • Node.js 18+
  • Also compatible with: Vercel, Cloudflare Workers, Deno v1.25+, Bun 1.0+, React Native

Installation

npm install @getbrevo/brevo

Quick start

Initialize the client and send your first email:

quick-start.ts
import { BrevoClient } from '@getbrevo/brevo';
const brevo = new BrevoClient({ apiKey: 'your-api-key' });
const result = await brevo.transactionalEmails.sendTransacEmail({
subject: 'Hello from Brevo!',
htmlContent: '<html><body><p>Hello,</p><p>This is my first transactional email.</p></body></html>',
sender: { name: 'Alex from Brevo', email: 'hello@brevo.com' },
to: [{ email: 'johndoe@example.com', name: 'John Doe' }],
});
console.log('Email sent. Message ID:', result.messageId);

Configuration

Pass options to the constructor to configure timeout, retries, and other settings:

configuration.ts
const brevo = new BrevoClient({
apiKey: 'your-api-key',
timeoutInSeconds: 30,
maxRetries: 3,
});

Constructor options

OptionTypeDefaultDescription
apiKeystringRequiredYour Brevo API key
timeoutInSecondsnumber60Default request timeout in seconds
maxRetriesnumber2Maximum retry attempts on retryable errors
baseUrlstringnullOverride the default API base URL
fetchtypeof fetchnullCustom fetch implementation
headersRecord<string, string>nullAdditional default headers sent with every request
loggingLogConfig | LoggernullLogging configuration

Error handling

The SDK throws typed error classes based on HTTP status codes:

error-handling.ts
import { Brevo, BrevoError } from '@getbrevo/brevo';
try {
await brevo.transactionalEmails.sendTransacEmail({ ... });
} catch (err) {
if (err instanceof Brevo.UnauthorizedError) {
console.error('Invalid API key');
} else if (err instanceof Brevo.TooManyRequestsError) {
const retryAfter = err.rawResponse.headers['retry-after'];
console.error(`Rate limited. Retry after ${retryAfter}s`);
} else if (err instanceof BrevoError) {
console.error(`API error ${err.statusCode}:`, err.message);
}
}

Error classes

Typed subclasses are namespaced under Brevo (e.g. Brevo.UnauthorizedError) — only BrevoError and BrevoTimeoutError are top-level exports.

Status codeClass
400Brevo.BadRequestError
401Brevo.UnauthorizedError
403Brevo.ForbiddenError
404Brevo.NotFoundError
422Brevo.UnprocessableEntityError
429Brevo.TooManyRequestsError
500+Brevo.InternalServerError

All BrevoError instances expose:

  • statusCode — HTTP status code
  • message — Error message
  • body — Parsed response body
  • rawResponse — Raw response with headers

Retries

Automatic retries with exponential backoff are enabled by default (2 retries). Configure at the client or request level:

retries.ts
// Client-level
const brevo = new BrevoClient({
apiKey: 'your-api-key',
maxRetries: 3,
});
// Request-level (overrides client setting)
await brevo.transactionalEmails.sendTransacEmail({ ... }, {
maxRetries: 0, // Disable retries for this request
});

Retry behavior

  • Retryable status codes: 408, 429, 500, 502, 503, 504
  • Backoff schedule: ~1s, ~2s, ~4s (exponential with jitter)
  • Rate limit headers: Respects Retry-After response header

Timeouts

Default timeout is 60 seconds. Configure at the client or request level:

timeouts.ts
// Client-level
const brevo = new BrevoClient({
apiKey: 'your-api-key',
timeoutInSeconds: 30,
});
// Request-level (overrides client setting)
await brevo.transactionalEmails.sendTransacEmail({ ... }, {
timeoutInSeconds: 10,
});
Use caseTimeout
Standard API calls30–60s (default)
Quick operations10–15s
Bulk operations120–300s
Real-time / low-latency5–10s

Request options

All service methods accept a request options object as the final argument:

request-options.ts
await brevo.transactionalEmails.sendTransacEmail({ ... }, {
timeoutInSeconds: 10,
maxRetries: 1,
headers: { 'X-Custom-Header': 'custom-value' },
queryParams: { customParam: 'value' },
});

Abort signal

Cancel in-flight requests using the Web AbortController API:

abort-signal.ts
const controller = new AbortController();
await brevo.transactionalEmails.sendTransacEmail({ ... }, {
abortSignal: controller.signal,
});
controller.abort(); // Cancel the request

Raw response

Access response headers and metadata via .withRawResponse():

raw-response.ts
const { data, rawResponse } = await brevo.transactionalEmails
.sendTransacEmail({ ... })
.withRawResponse();
console.log(rawResponse.headers['x-request-id']);
console.log(data.messageId);

Binary responses

Endpoints that return binary content (e.g., attachment downloads) expose multiple consumption methods:

binary-responses.ts
const response = await brevo.inboundParsing.getInboundEmailAttachment(downloadToken);
const stream = response.stream();
const arrayBuffer = await response.arrayBuffer();
const blob = await response.blob();
const bytes = await response.bytes();

Saving binary content

import { createWriteStream } from 'fs';
import { Readable } from 'stream';
import { pipeline } from 'stream/promises';
const stream = response.stream();
await pipeline(Readable.fromWeb(stream), createWriteStream('path/to/file'));
await Bun.write('path/to/file', response.stream());
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'filename';
a.click();
URL.revokeObjectURL(url);

TypeScript types

All request and response types are exported from the package:

typescript-types.ts
import type { Brevo } from '@getbrevo/brevo';
const request: Brevo.SendTransacEmailRequest = {
subject: 'First email',
textContent: 'Hello world!',
sender: { name: 'Bob Wilson', email: 'bob.wilson@brevo.com' },
to: [{ email: 'sarah.davis@example.com', name: 'Sarah Davis' }],
};

Logging

Configure logging to inspect outgoing requests and responses:

logging.ts
import { BrevoClient, logging } from '@getbrevo/brevo';
const brevo = new BrevoClient({
apiKey: 'your-api-key',
logging: {
level: logging.LogLevel.Debug,
logger: new logging.ConsoleLogger(),
},
});

Custom logger

Integrate with any logging library by implementing the ILogger interface:

custom-logger.ts
import winston from 'winston';
import { logging } from '@getbrevo/brevo';
const winstonLogger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [new winston.transports.Console()],
});
const logger: logging.ILogger = {
debug: (msg, ...args) => winstonLogger.debug(msg, ...args),
info: (msg, ...args) => winstonLogger.info(msg, ...args),
warn: (msg, ...args) => winstonLogger.warn(msg, ...args),
error: (msg, ...args) => winstonLogger.error(msg, ...args),
};
const brevo = new BrevoClient({
apiKey: 'your-api-key',
logging: { level: logging.LogLevel.Debug, logger },
});

Custom fetch

Override the default fetch implementation for any runtime or to add request interceptors:

custom-fetch.ts
const brevo = new BrevoClient({
apiKey: 'your-api-key',
fetch: async (url, options) => {
console.log('', url);
const response = await fetch(url, options);
console.log('', response.status);
return response;
},
});

Common integrations

import fetch from 'node-fetch';
const brevo = new BrevoClient({
apiKey: 'your-api-key',
fetch: fetch as typeof globalThis.fetch,
});
import { fetch } from 'undici';
const brevo = new BrevoClient({
apiKey: 'your-api-key',
fetch: fetch as typeof globalThis.fetch,
});
import { randomUUID } from 'crypto';
const brevo = new BrevoClient({
apiKey: 'your-api-key',
fetch: async (url, options) => {
return fetch(url, {
...options,
headers: {
...options?.headers,
'X-Request-ID': randomUUID(),
},
});
},
});

Available services

The BrevoClient exposes the following service namespaces:

PropertyDescription
transactionalEmailsSend emails, manage templates, blocked contacts and domains
transactionalSmsSend SMS messages and view delivery statistics
transactionalWhatsAppSend WhatsApp messages and view event reports
smsTemplatesManage SMS templates
contactsManage contacts, lists, folders, attributes and segments
emailCampaignsCreate and manage email marketing campaigns
smsCampaignsCreate and manage SMS marketing campaigns
whatsAppCampaignsCreate and manage WhatsApp campaigns and templates
companiesManage CRM companies
dealsManage CRM deals and pipelines
tasksManage CRM tasks
notesManage CRM notes
filesUpload and manage CRM files
conversationsManage conversation messages and automated messages
ecommerceManage products, categories, orders and attribution
couponsManage coupon collections and coupons
paymentsCreate and manage payment requests
eventTrack custom events
webhooksManage webhooks
sendersManage senders and IPs
domainsManage and authenticate domains
accountRetrieve account information and activity logs
inboundParsingRetrieve inbound email events and attachments
customObjectsManage custom object records
externalFeedsManage external RSS feeds
masterAccountManage sub-accounts and groups (enterprise)
userManage users and permissions
processRetrieve background process status
programManage loyalty programs
balanceManage loyalty balances and transactions
rewardManage loyalty rewards and vouchers
tierManage loyalty tiers and tier groups

Migration from v3.x

Key changes

Areav3.xv5.x
Clientnew TransactionalEmailsApi() per resourcenew BrevoClient({ apiKey }) unified
Auth(api as any).authentications.apiKey.apiKey = "..."Constructor option
API styleClass-based with settersPromise-based with inline objects
TypeScriptPartialFull, exported types
RetriesNot built-inAutomatic with exponential backoff

Migration example

// v3.x
import { TransactionalEmailsApi, SendSmtpEmail } from '@getbrevo/brevo';
let emailAPI = new TransactionalEmailsApi();
(emailAPI as any).authentications.apiKey.apiKey = 'xkeysib-xxx';
let message = new SendSmtpEmail();
message.subject = 'First email';
message.textContent = 'Hello world!';
message.sender = { name: 'Bob Wilson', email: 'bob.wilson@brevo.com' };
message.to = [{ email: 'sarah.davis@example.com', name: 'Sarah Davis' }];
emailAPI.sendTransacEmail(message);

Resources