MCPcopy Index your code
hub / github.com/stripe/stripe-node

github.com/stripe/stripe-node @v22.3.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v22.3.0 ↗ · + Follow
4,996 symbols 6,655 edges 312 files 678 documented · 14% updated 4d agov22.4.0-alpha.2 · 2026-07-02★ 4,45938 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Stripe Node.js Library

Version Build Status Downloads

[!TIP] Want to chat live with Stripe engineers? Join us on our Discord server.

The Stripe Node library provides convenient access to the Stripe API from applications written in server-side JavaScript.

For collecting customer and payment information in the browser, use [Stripe.js][stripe-js].

Documentation

See the stripe-node API docs for Node.js.

Requirements

Per our Language Version Support Policy, we currently support all LTS versions of Node.js 18+.

Read more and see the full schedule in the docs: https://docs.stripe.com/sdks/versioning?lang=node#stripe-sdk-language-version-support-policy

Installation

Install the package with:

npm install stripe
# or
yarn add stripe

Usage

The package needs to be configured with your account's secret key, which is available in the [Stripe Dashboard][api-keys]. Require it with the key's value:

import Stripe from 'stripe';
const stripeClient = new Stripe('sk_test_...');

const customer = await stripeClient.customers.create({
  email: 'customer@example.com',
});

console.log(customer.id);

Or using CJS:

const Stripe = require('stripe');
const stripeClient = Stripe('sk_test_...');

stripeClient.customers
  .create({
    email: 'customer@example.com',
  })
  .then((customer) => console.log(customer.id))
  .catch((error) => console.error(error));

[!WARNING] If you're using v17.x.x or later and getting an error about a missing API key despite being sure it's available, it's likely you're importing the file that instantiates Stripe while the key isn't present (for instance, during a build step). If that's the case, consider instantiating the client lazily:

```ts import Stripe from 'stripe';

let _stripe: Stripe | null = null; const getStripeClient = (): Stripe => { if (!_stripe) { _stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string, { // ... }); } return _stripe; };

const getCustomers = () => getStripeClient().customers.list(); ```

Alternatively, you can provide a placeholder for the real key (which will be enough to get the code through a build step):

```ts import Stripe from 'stripe';

export const stripeClient = new Stripe( process.env.STRIPE_SECRET_KEY || 'api_key_placeholder', { // ... } ); ```

Usage with TypeScript

As of 8.0.1, Stripe maintains types for the latest [API version][api-versions].

Import Stripe as a default import (not * as Stripe, unlike the DefinitelyTyped version) and instantiate it as new Stripe() with the latest API version.

import Stripe from 'stripe';
const stripeClient = new Stripe('sk_test_...');

const createCustomer = async () => {
  const params: Stripe.CustomerCreateParams = {
    description: 'test customer',
  };

  const customer: Stripe.Customer = await stripeClient.customers.create(params);

  console.log(customer.id);
};
createCustomer();

You can find a full TS server example in stripe-samples.

Using old API versions with TypeScript

Types can change between API versions (e.g., Stripe may have changed a field from a string to a hash), so our types only reflect the latest API version.

We therefore encourage [upgrading your API version][api-version-upgrading] if you would like to take advantage of Stripe's TypeScript definitions.

If you are on an older API version (e.g., 2019-10-17) and not able to upgrade, you may pass another version and use a comment like // @ts-ignore stripe-version-2019-10-17 to silence type errors here and anywhere the types differ between your API version and the latest. When you upgrade, you should remove these comments.

We also recommend using // @ts-ignore if you have access to a beta feature and need to send parameters beyond the type definitions.

Using expand with TypeScript

[Expandable][expanding_objects] fields are typed as string | Foo, so you must cast them appropriately, e.g.,

const paymentIntent: Stripe.PaymentIntent = await stripeClient.paymentIntents.retrieve(
  'pi_123456789',
  {
    expand: ['customer'],
  }
);
const customerEmail: string = (paymentIntent.customer as Stripe.Customer).email;

// Define and use this helper method if you extract `id` often
function getId(stripeObject: {id: string} | string) {
  return typeof stripeObject === 'string' ? stripeObject : stripeObject.id;
}

const customerId: string = getId(paymentIntent.customer);

TypeScript and the stripe-node versioning policy

The TypeScript types in stripe-node always reflect the latest shape of the Stripe API. When the Stripe API changes in a backwards-incompatible way, there is a new Stripe API version, and we release a new major version of stripe-node. Sometimes, though, the Stripe API changes in a way that weakens the guarantees provided by the TypeScript types, but that cannot result in any backwards incompatibility at runtime. For example, we might add a new enum value on a response, along with a new parameter to a request. Adding a new value to a response enum weakens the TypeScript type. However, if the new enum value is only returned when the new parameter is provided, this cannot break any existing usages and so would not be considered a breaking API change. In stripe-node, we do NOT consider such changes to be breaking under our current versioning policy. This means that you might see new type errors from TypeScript as you upgrade minor versions of stripe-node, that you can resolve by adding additional type guards.

Please feel welcome to share your thoughts about the versioning policy in a Github issue. For now, we judge it to be better than the two alternatives: outdated, inaccurate types, or vastly more frequent major releases, which would distract from any future breaking changes with potentially more disruptive runtime implications.

Using Promises

Every method returns a chainable promise which can be used instead of a regular callback:

// Create a new customer and then create an invoice item then invoice it:
stripeClient.customers
  .create({
    email: 'customer@example.com',
  })
  .then((customer) => {
    // have access to the customer object
    return stripe.invoiceItems
      .create({
        customer: customer.id, // set the customer id
        amount: 2500, // 25
        currency: 'usd',
        description: 'One-time setup fee',
      })
      .then((invoiceItem) => {
        return stripe.invoices.create({
          collection_method: 'send_invoice',
          customer: invoiceItem.customer,
        });
      })
      .then((invoice) => {
        // New invoice created on a new customer
      })
      .catch((err) => {
        // Deal with an error
      });
  });

Usage with Deno

As of 11.16.0, stripe-node provides a deno export target. In your Deno project, import stripe-node using an npm specifier:

Import using npm specifiers:

import Stripe from 'npm:stripe';

Please see https://github.com/stripe-samples/stripe-node-deno-samples for more detailed examples and instructions on how to use stripe-node in Deno.

Configuration

Initialize with config object

The package can be initialized with several options:

import ProxyAgent from 'https-proxy-agent';

const stripe = Stripe('sk_test_...', {
  maxNetworkRetries: 1,
  httpAgent: new ProxyAgent(process.env.http_proxy),
  timeout: 1000,
  host: 'api.example.com',
  port: 123,
  telemetry: true,
});
Option Default Description
apiVersion null Stripe API version to be used. If not set, stripe-node will use the latest version at the time of release.
maxNetworkRetries 1 The amount of times a request should be retried.
httpAgent null Proxy agent to be used by the library.
timeout 80000 Maximum time each request can take in ms.
host 'api.stripe.com' Host that requests are made to.
port 443 Port that requests are made to.
protocol 'https' 'https' or 'http'. http is never appropriate for sending requests to Stripe servers, and we strongly discourage http, even in local testing scenarios, as this can result in your credentials being transmitted over an insecure channel.
telemetry true Allow Stripe to send telemetry.

Note Both maxNetworkRetries and timeout can be overridden on a per-request basis.

Configuring Timeout

Timeout can be set globally via the config object:

const stripeClient = Stripe('sk_test_...', {
  timeout: 20 * 1000, // 20 seconds
});

And overridden on a per-request basis:

stripeClient.customers.create(
  {
    email: 'customer@example.com',
  },
  {
    timeout: 1000, // 1 second
  }
);

Configuring For Connect

A per-request Stripe-Account header for use with [Stripe Connect][connect] can be added to any method:

// List the balance transactions for a connected account:
stripeClient.balanceTransactions.list(
  {
    limit: 10,
  },
  {
    stripeAccount: 'acct_foo',
  }
);

Configuring a Proxy

To use stripe behind a proxy you can pass an [https-proxy-agent][https-proxy-agent] on initialization:

if (process.env.http_proxy) {
  const ProxyAgent = require('https-proxy-agent');

  const stripe = Stripe('sk_test_...', {
    httpAgent: new ProxyAgent(process.env.http_proxy),
  });
}

Network retries

As of v13 stripe-node will automatically do one reattempt for failed requests that are safe to retry. Automatic network retries can be disabled by setting the maxNetworkRetries config option to 0. You can also set a higher number to reattempt multiple times, with exponential backoff. Idempotency keys are added where appropriate to prevent duplication.

const stripeClient = Stripe('sk_test_...', {
  maxNetworkRetries: 0, // Disable retries
});
const stripeClient = Stripe('sk_test_...', {
  maxNetworkRetries: 2, // Retry a request twice before giving up
});

Network retries can also be set on a per-request basis:

stripeClient.customers.create(
  {
    email: 'customer@example.com',
  },
  {
    maxNetworkRetries: 2, // Retry this specific request twice before giving up
  }
);

Examining Responses

Some information about the response which generated a resource is available with the lastResponse property:

customer.lastResponse.requestId; // see: https://stripe.com/docs/api/request_ids?lang=node
customer.lastResponse.statusCode;

request and response events

The Stripe object emits request and response events. You can use them like this:

const Stripe = require('stripe');
const stripeClient = Stripe('sk_test_...');

const onRequest = (request) => {
  // Do something.
};

// Add the event handler function:
stripeClient.on('request', onRequest);

// Remove the event handler function:
stripeClient.off('request', onRequest);

request object

```js { api_version: 'latest', account: 'acct_TEST', // Only present if provided idem

Extension points exported contracts — how you extend this code

HttpClientInterface (Interface)
(no doc) [1 implementers]
src/net/HttpClient.ts
StripeConfig (Interface)
(no doc)
src/lib.ts
Metadata (Interface)
(no doc)
src/shared.ts
StripeConstructor (Interface)
(no doc)
src/stripe.cjs.node.ts
DecimalRoundingOptions (Interface)
(no doc)
src/Decimal.ts
Product (Interface)
(no doc)
src/resources/Products.ts
HttpClientResponseInterface (Interface)
(no doc) [1 implementers]
src/net/HttpClient.ts
RequestOptions (Interface)
(no doc)
src/lib.ts

Core symbols most depended-on inside this repo

_makeRequest
called by 589
src/StripeResource.ts
create
called by 179
src/resources/Files.ts
toString
called by 155
src/Decimal.ts
retrieve
called by 145
src/resources/Files.ts
list
called by 115
src/resources/Files.ts
update
called by 56
src/resources/Plans.ts
post
called by 54
src/resources/TestHelpers/Treasury/OutboundPayments.ts
parse
called by 51
src/StripeContext.ts

Shape

Interface 3,511
Method 900
Class 438
Function 147

Languages

TypeScript100%

Modules by API surface

src/resources/Events.ts271 symbols
src/resources/Accounts.ts169 symbols
src/resources/PaymentIntents.ts160 symbols
src/resources/Checkout/Sessions.ts150 symbols
src/resources/V2/Core/Accounts.ts137 symbols
src/resources/V2/Core/Events.ts133 symbols
src/resources/Tax/Registrations.ts119 symbols
src/resources/Invoices.ts117 symbols
src/resources/PaymentRecords.ts111 symbols
src/resources/Charges.ts110 symbols
src/resources/SetupIntents.ts105 symbols
src/resources/PaymentAttemptRecords.ts96 symbols

Dependencies from manifests, versioned

@nestjs/common11.0.16 · 1×
@nestjs/config3.0.0 · 1×
@nestjs/core10.2.1 · 1×
@nestjs/platform-express10.2.1 · 1×
@types/chai4.3.4 · 1×
@types/chai-as-promised7.1.5 · 1×
@types/koa2.13.5 · 1×
@types/koa-bodyparser4.3.10 · 1×
@types/mocha10.0.1 · 1×
@types/node22 · 1×
@types/react18.0.27 · 1×

For agents

$ claude mcp add stripe-node \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact