npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

chargebee

v3.16.0

Published

A library for integrating with Chargebee.

Readme

Chargebee Node.js / TypeScript Client Library

[!NOTE] Join Discord

We are trialing a Discord server for developers building with Chargebee. Limited spots are open on a first-come basis. Join here if interested.

[!TIP] If you are using Next.js or Express, check out chargebee-init to get started quickly with the adapters for these frameworks. Learn more about it in this tutorial.

  • 📘 For a complete reference of available APIs, check out our API Documentation.
  • 🧪 To explore and test API capabilities interactively, head over to our API Explorer.

If you're upgrading from an older version of chargebee-typescript or chargebee, please refer to the Migration Guide.

Requirements

Node.js 18 or higher.

Installation

Install the library with npm:

npm install chargebee

With pnpm:

pnpm add chargebee

With yarn:

yarn add chargebee

Usage

The package needs to be configured with your site's API key, which is available under Configure Chargebee Section. Refer here for more details.

If you're using ESM / TypeScript:

import Chargebee from 'chargebee';

const chargebee = new Chargebee({
  site: "{{site}}",
  apiKey: "{{api-key}}",
});

Or using Common JS module system:

const Chargebee = require('chargebee');

const chargebee = new Chargebee({
  site: "{{site}}",
  apiKey: "{{api-key}}",
});

Using Async / Await

try {
  const { customer } = await chargebee.customer.create({
    email: "[email protected]"
    // other params
  });
} catch (err) {
  // handle error
}

Using filters in the List API

For pagination, offset is the parameter that is being used. The value used for this parameter must be the value returned for next_offset parameter in the previous API call.

async function getAllCustomers() {
  const allCustomers: Customer[] = [];
  let offset: string | undefined = undefined;

  do {
    const listCustomersReponse = await chargebee.customer.list({
      limit: 2,
      offset,
      first_name: {
        is: "John"
      }
    });

    const customers = listCustomersReponse.list.map(
      (object) => object.customer
    );
    
    allCustomers.push(...customers);
    offset = listCustomersReponse.next_offset;
  } while (offset);

  console.log(allCustomers);
}

Using custom headers and custom fields

const { customer } = await chargebee.customer.create(
  {
    email: "[email protected]",
    cf_host_url: "http://xyz.com" // `cf_host_url` is a custom field in Customer object
  },
  {
    "chargebee-event-email": "all-disabled" // To disable webhooks
  }
);

Creating an idempotent request

Idempotency keys are passed along with request headers to allow a safe retry of POST requests.

const { customer, isIdempotencyReplayed } = await chargebee.customer.create(
  { email: "[email protected]" },
  {
    "chargebee-idempotency-key": "eBs7iOFQuR7asUKHfddyxDDerOuF1JtFrLmDI" // Add idempotency key
  }
);
console.log("isIdempotencyReplayed: ", isIdempotencyReplayed);

Creating multiple instances of Chargebee for different sites

const chargebeeSiteUS = new Chargebee({
  apiKey: "{api-key}",
  site: "my-site-us"
});

const chargebeeSiteEU = new Chargebee({
  apiKey: "{api-key}",
  site: "my-site-eu"
});

Processing Webhooks - API Version Check

An attribute api_version is added to the Event resource, which indicates the API version based on which the event content is structured. In your webhook servers, ensure this api_version is the same as the API version used by your webhook server's client library.

Retry Handling

Chargebee's SDK includes built-in retry logic to handle temporary network issues and server-side errors. This feature is disabled by default but can be enabled when needed.

Key features include:

  • Automatic retries for specific HTTP status codes: Retries are automatically triggered for status codes 500, 502, 503, and 504.
  • Exponential backoff: Retry delays increase exponentially to prevent overwhelming the server.
  • Rate limit management: If a 429 Too Many Requests response is received with a Retry-After header, the SDK waits for the specified duration before retrying.

    Note: Exponential backoff and max retries do not apply in this case.

  • Customizable retry behavior: Retry logic can be configured using the retryConfig parameter in the environment configuration.

Example: Customizing Retry Logic

You can enable and configure the retry logic by passing a retryConfig object when initializing the Chargebee environment:

import Chargebee from 'chargebee';

const chargebee = new Chargebee({
  site: "{{site}}",
  apiKey: "{{api-key}}",
  retryConfig: {
    enabled: true, // Enable retry logic
    maxRetries: 5, // Maximum number of retries
    delayMs: 300, // Initial delay between retries in milliseconds
    retryOn: [500, 502, 503, 504], // HTTP status codes to retry on
  },
});

try {
  const { customer } = await chargebee.customer.create({
    email: "[email protected]",
  });
  console.log("Customer created:", customer);
} catch (err) {
  console.error("Request failed after retries:", err);
}

Example: Rate Limit retry logic

You can enable and configure the retry logic for rate-limit by passing a retryConfig object when initializing the Chargebee environment:

import Chargebee from 'chargebee';

const chargebee = new Chargebee({
  site: "{{site}}",
  apiKey: "{{api-key}}",
  retryConfig: {
    enabled: true,
    retryOn: [429], 
  },
});

try {
  const { customer } = await chargebee.customer.create({
    email: "[email protected]",
  });
  console.log("Customer created:", customer);
} catch (err) {
  console.error("Request failed after retries:", err);
}

Webhook Type Mapping

To improve type safety and gain better autocompletion when working with webhooks, you can leverage the WebhookEvent resource. This allows you to strongly type the event content for a particular webhook event.

Example

import Chargebee, { type WebhookContentType, WebhookEvent } from "chargebee";

const result = await chargebeeInstance.event.retrieve("{event-id}");
const subscripitonActivatedEvent: WebhookEvent<WebhookContentType.SubscriptionActivated> = result.event;
const subscription = subscripitonActivatedEvent.content.subscription;

Notes

  • WebhookEvent<T> provides type hinting for the event payload, making it easier to work with specific event structures.
  • Use the WebhookContentType to specify the exact event type (e.g., SubscriptionCreated, InvoiceGenerated, etc.).
  • This approach ensures you get proper IntelliSense and compile-time checks when accessing event fields.

Custom HTTP Client

The SDK supports injecting a custom HTTP client, giving you full flexibility to control how API requests are made and handled. This feature is useful if you want to integrate your own networking stack, add custom logging, implement telemetry, or handle retries in a specific way.

With this enhancement, you can replace the default HTTP client with your own implementation by passing a custom client that adheres to the HttpClientInterface contract when initializing the Chargebee instance.

const chargebee = new Chargebee({
    site: "{site}",
    apiKey: "{key}",
    httpClient: new CustomHttpClient(),
});

Notes

  • Your custom client must implement the HttpClientInterface provided by the SDK.

  • This feature is especially useful in environments with strict networking policies or where advanced observability is required.

  • Example implementations are available under:

  • You may need to implement custom conversion logic when integrating third-party HTTP libraries, as their request and response formats might not directly align with the HttpClientInterface expected by the SDK.

These examples demonstrate how to implement and inject custom clients using axios and ky, respectively.

Feedback

If you find any bugs or have any questions / feedback, open an issue in this repository or reach out to us on [email protected]

v2

Chargebee Node SDK v2 is deprecated. If you using v2, follow this guide to migrate to v3.