@getbrevo/brevo

中文文档
6.2.0发布于 2026/10/16TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 176.5万

Brevo SDK for Node.js with TypeScript support.

原始使用文档
文档目录26 节
  1. Installation
  2. Quick Start
  3. Configuration
  4. Constructor options
  5. Authentication
  6. API key
  7. OAuth 2.0 machine-to-machine (M2M)
  8. Error Handling
  9. Retries
  10. Timeouts
  11. Request Options
  12. Additional Headers
  13. Query Parameters
  14. Abort Signal
  15. Raw Response
  16. Binary Responses
  17. TypeScript Types
  18. Logging
  19. Custom Fetch Client
  20. Runtime Compatibility
  21. Upgrading from v5.x
  22. Breaking changes
  23. Added
  24. Migration from v3.x
  25. Contributing
  26. Support

Brevo Node.js SDK

fern shield License: MIT npm version npm downloads

Website • API Reference • Support


Installation

npm install @getbrevo/brevo

Quick Start

import { BrevoClient } from '@getbrevo/brevo';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
});

const result = await brevo.transactionalEmails.sendTransacEmail({
  subject: "Hello",
  textContent: "Hello world!",
  sender: { name: "Sender", email: "[email protected]" },
  to: [{ email: "[email protected]" }]
});

console.log('Email sent:', result);

Configuration

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

Constructor options

OptionTypeDefaultDescription
apiKeystringnullYour Brevo API key. See Authentication.
clientIdstringBREVO_CLIENT_ID env varOAuth 2.0 M2M app client ID
clientSecretstringBREVO_CLIENT_SECRET env varOAuth 2.0 M2M app client secret
tokenstringnullAn OAuth access token you already have (not refreshed by the SDK)
authAuthProvidernullCustom auth provider (dynamic tokens, key rotation).
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

Authentication

The client supports two authentication methods. Use one per client.

API key

import { BrevoClient } from '@getbrevo/brevo';

const brevo = new BrevoClient({ apiKey: 'xkeysib-xxx' });

Create an API key in your Brevo account at app.brevo.com/settings/keys/api. See API key authentication.

OAuth 2.0 machine-to-machine (M2M)

Pass the client ID and secret of an M2M app. The client exchanges them for an access token on the first request, reuses the token, and fetches a new one shortly before it expires (tokens are valid for about one hour).

import { BrevoClient } from '@getbrevo/brevo';

const brevo = new BrevoClient({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
});

const account = await brevo.account.getAccount();

Or set BREVO_CLIENT_ID and BREVO_CLIENT_SECRET in the environment and create the client without arguments:

const brevo = new BrevoClient();

If you already have an access token, pass it directly. The client sends it as-is and does not refresh it:

const brevo = new BrevoClient({ token: 'your-access-token' });

A token requested by the client carries every scope granted to the app. To create an M2M app and choose its scopes, or to request a token with specific scopes, see Machine-to-machine (M2M) authentication.

Error Handling

The SDK throws specific error types based on HTTP status codes.

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} seconds`);
  } else if (err instanceof BrevoError) {
    console.error(`API Error ${err.statusCode}:`, err.message);
  }
}

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

Error Types:

  • 400 - Brevo.BadRequestError
  • 401 - Brevo.UnauthorizedError
  • 403 - Brevo.ForbiddenError
  • 404 - Brevo.NotFoundError
  • 422 - Brevo.UnprocessableEntityError
  • 429 - Brevo.TooManyRequestsError
  • 500+ - Brevo.InternalServerError
Error properties

All BrevoError instances provide:

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

Retries

Automatic retries with exponential backoff are enabled by default (2 retries).

// Client-level
const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  maxRetries: 3
});

// Request-level
await brevo.transactionalEmails.sendTransacEmail({...}, {
  maxRetries: 5
});

Retryable status codes: 408, 429, 500, 502, 503, 504

How retries work
  • Exponential backoff: ~1s, ~2s, ~4s (with jitter)
  • Respects Retry-After header for rate limits
  • Can be disabled per request with maxRetries: 0

Timeouts

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

// Client-level
const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  timeoutInSeconds: 30
});

// Request-level
await brevo.transactionalEmails.sendTransacEmail({...}, {
  timeoutInSeconds: 10
});

Recommended values:

  • Standard API calls: 30-60s (default)
  • Quick operations: 10-15s
  • Bulk operations: 120-300s
  • Real-time: 5-10s

Request Options

Additional Headers

await brevo.transactionalEmails.sendTransacEmail({...}, {
  headers: {
    'X-Custom-Header': 'custom-value'
  }
});

Query Parameters

await brevo.transactionalEmails.sendTransacEmail({...}, {
  queryParams: {
    'customParam': 'value'
  }
});

Abort Signal

const controller = new AbortController();
await brevo.transactionalEmails.sendTransacEmail({...}, {
  abortSignal: controller.signal
});
controller.abort();

Raw Response

const { data, rawResponse } = await brevo.transactionalEmails.sendTransacEmail({...})
  .withRawResponse();

console.log(rawResponse.headers['X-My-Header']);

Binary Responses

const response = await brevo.inboundParsing.getInboundEmailAttachment(...);

// Choose one:
const stream = response.stream();
// const arrayBuffer = await response.arrayBuffer();
// const blob = await response.blob();
// const bytes = await response.bytes();
Save to file examples

Node.js (ReadableStream):

import { createWriteStream } from 'fs';
import { Readable } from 'stream';
import { pipeline } from 'stream/promises';

const stream = response.stream();
const nodeStream = Readable.fromWeb(stream);
await pipeline(nodeStream, createWriteStream('path/to/file'));

Bun:

await Bun.write('path/to/file', response.stream());

Browser:

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.

import { BrevoClient } from '@getbrevo/brevo';

const request: Brevo.SendTransacEmailRequest = {
  subject: "First email",
  textContent: "Hello world!",
  sender: { name: "Bob Wilson", email: "[email protected]" },
  to: [{ email: "[email protected]", name: "Sarah Davis" }]
};

Logging

import { BrevoClient, logging } from '@getbrevo/brevo';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  logging: {
    level: logging.LogLevel.Debug,
    logger: new logging.ConsoleLogger(),
    silent: false
  }
});
Custom logger example
import winston from 'winston';

const winstonLogger = winston.createLogger({...});

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),
};

Custom Fetch Client

Override the default fetch implementation for advanced use cases.

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 use cases

Using node-fetch:

import fetch from 'node-fetch';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  fetch: fetch as typeof globalThis.fetch,
});

Using undici:

import { fetch } from 'undici';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  fetch: fetch as typeof globalThis.fetch,
});

With a request ID header:

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(),
      },
    });
  },
});

Runtime Compatibility

  • Node.js 18+
  • Vercel
  • Cloudflare Workers
  • Deno v1.25+
  • Bun 1.0+
  • React Native

Upgrading from v5.x

v6 is a major release. Most breaking changes come from an internal effort at Brevo to make endpoints, parameters and models more self-descriptive — so names, shapes and required fields convey intent without needing to cross-reference external docs (both for developers and for AI agents working against the Brevo API).

v5.x remains supported. If you need to hold on v5 temporarily, pin it:

npm install @getbrevo/brevo@^5.0
View v5 → v6 migration guide

Breaking changes

Companies — getCompanies filter parameter renamed

// v5
await brevo.companies.getCompanies({ filters: 'foo' });

// v6
await brevo.companies.getCompanies({ 'filters[attributes.name]': 'foo' });

The old filters name still compiles but the filter is silently dropped server-side and you get an unfiltered list. Audit every call site.

Events — createBatchEvents payload shape

// v5
await brevo.event.createBatchEvents([{ /* event */ }]);

// v6
await brevo.event.createBatchEvents({ events: [{ /* event */ }] });

Balance — getActiveBalancesApi response & parameter rename

  • Response type replaced: BalanceLimit → GetLoyaltyBalanceProgramsPidActiveBalanceResponse.
  • Parameters renamed from snake_case to camelCase: contact_id → contactId, balance_definition_id → balanceDefinitionId, sort_field → sortField.

Balance — getContactBalances requires balanceDefinitionId

CRM — getCrmTasktypes returns an array (GetCrmTasktypesResponseItem[]).

Model fields removed: GetWebhook.channel, GetProcessResponseInfo.export, GetEventsList.events[].source, GetExtendedCampaignOverview.utmIDActive (replaced by utmID: number).

Model fields renamed: ConversationsMessage.File.filename → name, .url → link; SendTransacSms.tag is now string | string[].

Now-required fields: GetContactDetails.whatsappBlacklisted, Note.text, Task.date.

Added

  • BrevoClient accepts a new auth option for custom AuthProvider injection (existing apiKey continues to work unchanged).
  • New optional fields and filters across contacts.createContact, contacts.updateContact, emailCampaigns.getEmailCampaigns, ecommerce.getProducts, and several other endpoints.

Migration from v3.x

View migration guide

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: "[email protected]" };
message.to = [{ email: "[email protected]", name: "Sarah Davis" }];

emailAPI.sendTransacEmail(message);

v6.x:

import { BrevoClient } from '@getbrevo/brevo';

const brevo = new BrevoClient({
  apiKey: 'xkeysib-xxx',
});

await brevo.transactionalEmails.sendTransacEmail({
  subject: "First email",
  textContent: "Hello world!",
  sender: { name: "Bob Wilson", email: "[email protected]" },
  to: [{ email: "[email protected]", name: "Sarah Davis" }],
});

[!WARNING] The legacy v3.x SDK (@getbrevo/brevo@^3.0.1) will continue to receive critical security updates but no new features. We recommend migrating to v6.x.


Contributing

This library is generated programmatically. Changes made directly to the library would be overwritten. Please open an issue first to discuss changes.

Contributions to this README are always welcome!


Support

版本与发布记录

@getbrevo/brevo 共发布 22 个版本,首次发布于 2023/06/14;过去 12 个月发布了 12 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
6.2.0latest2026/10/1630 天前
6.1.02026/10/141 个月前
6.0.32026/08/103 个月前
6.0.22026/07/034 个月前
6.0.1next2026/05/156 个月前
5.0.42026/04/107 个月前

其他发布通道:legacy → 3.0.1,skip → 3.0.2,broken → 3.0.2,next → 6.0.1。

关于 @getbrevo/brevo 的常见问题

@getbrevo/brevo 是什么?

Brevo SDK for Node.js with TypeScript support.

如何安装 @getbrevo/brevo?

在项目目录运行 npm install @getbrevo/brevo,或使用 pnpm add / yarn add / bun add。

@getbrevo/brevo 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@getbrevo/brevo 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@getbrevo/brevo 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@getbrevo/brevo 可以商用吗?

@getbrevo/brevo 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@getbrevo/brevo 的下载量有多少?

根据 npm 官方下载统计,@getbrevo/brevo 在 2026/10/17 – 2026/11/15 这 30 天内被下载 1,764,773 次,日均约 58,826 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@getbrevo/brevo 还在维护吗?

最新版本 6.2.0 发布于 2026/10/16(30 天前);至今共发布 22 个版本,其中过去 12 个月发布了 12 个;首次发布于 2023/06/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。