# How to create a Stripe customer programmatically

- Tool: Stripe
- Difficulty: Beginner
- Time required: 15 minutes
- Compatibility: Stripe API v2024-12+, Node.js 18+, any backend framework
- Last updated: March 2026

## TL;DR

Create Stripe customers programmatically using stripe.customers.create() in Node.js. Pass email, name, metadata, and optionally attach a payment method in the same call. This is essential for automating signups, linking users to your database, and enabling recurring billing without manual Dashboard work.

## Programmatic Customer Creation in Stripe

When users sign up for your app, you need to create a matching Stripe customer record automatically. The stripe.customers.create() method accepts email, name, phone, address, metadata, and even a default payment method. By creating customers in code rather than the Dashboard, you can link each Stripe customer to your internal user ID, attach payment methods at signup, and set up subscriptions immediately — all in a single API flow.

## Before you start

- A Stripe account with API keys from Dashboard → Developers → API keys
- Node.js 18 or newer installed
- The stripe npm package installed (npm install stripe)
- A basic understanding of async/await in JavaScript

## Step-by-step guide

### 1. Initialize Stripe on your server

Import the Stripe library and initialize it with your secret key from environment variables.

```
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
```

**Expected result:** The stripe object is ready for API calls.

### 2. Create a basic customer

Call stripe.customers.create() with the customer's email and name. The API returns the full customer object including the unique cus_ ID.

```
const customer = await stripe.customers.create({
  email: 'alice@example.com',
  name: 'Alice Smith',
  phone: '+15551234567',
  metadata: {
    app_user_id: 'usr_98765',
    signup_source: 'web',
  },
});

console.log(customer.id); // cus_...
```

**Expected result:** A new customer is created and the cus_ ID is logged.

### 3. Create a customer with a payment method

If you collected a payment method via Stripe Elements on the frontend (which gives you a pm_ token), attach it during customer creation by setting payment_method and invoice_settings.default_payment_method.

```
const customer = await stripe.customers.create({
  email: 'bob@example.com',
  name: 'Bob Jones',
  payment_method: 'pm_card_visa', // from frontend
  invoice_settings: {
    default_payment_method: 'pm_card_visa',
  },
});
```

**Expected result:** The customer is created with the payment method attached and set as default.

### 4. Prevent duplicate customers

Before creating a new customer, search by email to see if one already exists. Stripe does not enforce unique emails, so this check is your responsibility.

```
async function findOrCreateCustomer(email, name) {
  const existing = await stripe.customers.list({ email, limit: 1 });
  if (existing.data.length > 0) {
    return existing.data[0];
  }
  return stripe.customers.create({ email, name });
}
```

**Expected result:** Returns the existing customer if found, or creates and returns a new one.

### 5. Test with the Stripe test card

In test mode, use pm_card_visa as a test payment method token, or create a PaymentMethod with card number 4242424242424242 to verify the full flow.

```
// Use the built-in test payment method
const customer = await stripe.customers.create({
  email: 'test@example.com',
  name: 'Test User',
  payment_method: 'pm_card_visa',
  invoice_settings: { default_payment_method: 'pm_card_visa' },
});
```

**Expected result:** A test customer is created with a Visa test card attached.

## Complete code example

File: `customer-service.js`

```javascript
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

const app = express();
app.use(express.json());

// Find or create a customer
async function findOrCreateCustomer(email, name, metadata) {
  const existing = await stripe.customers.list({ email, limit: 1 });
  if (existing.data.length > 0) {
    return { customer: existing.data[0], isNew: false };
  }
  const customer = await stripe.customers.create({
    email,
    name,
    metadata: metadata || {},
  });
  return { customer, isNew: true };
}

// Create customer endpoint
app.post('/api/customers', async (req, res) => {
  try {
    const { email, name, paymentMethodId, metadata } = req.body;

    if (!email) {
      return res.status(400).json({ error: 'Email is required' });
    }

    const { customer, isNew } = await findOrCreateCustomer(email, name, metadata);

    // Attach payment method if provided
    if (paymentMethodId && isNew) {
      await stripe.paymentMethods.attach(paymentMethodId, {
        customer: customer.id,
      });
      await stripe.customers.update(customer.id, {
        invoice_settings: { default_payment_method: paymentMethodId },
      });
    }

    res.json({
      id: customer.id,
      email: customer.email,
      name: customer.name,
      isNew,
    });
  } catch (err) {
    console.error('Customer creation error:', err.message);
    res.status(500).json({ error: err.message });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server on port ${PORT}`));
```

## Common mistakes

- **Not checking for existing customers before creating** — undefined Fix: Always search by email with stripe.customers.list({ email }) first. Stripe allows duplicates, which causes billing confusion.
- **Forgetting to store the Stripe customer ID in your database** — undefined Fix: Save customer.id alongside your user record immediately after creation. Without it, you cannot link future charges or subscriptions.
- **Attaching a payment method without setting it as default** — undefined Fix: After attaching a payment method, update the customer's invoice_settings.default_payment_method so it is used automatically for invoices and subscriptions.
- **Creating customers from the frontend** — undefined Fix: Customer creation requires your secret key (sk_). Always create customers from your server, never from client-side code.

## Best practices

- Always deduplicate customers by email before calling stripe.customers.create()
- Store customer.id in your database immediately after creation for future reference
- Use metadata to store your internal user ID, plan type, or signup source
- Attach a payment method during creation for a smoother checkout experience later
- Set invoice_settings.default_payment_method when attaching a card
- Use environment variables for your secret key — never hardcode sk_ values
- Log customer creation events for debugging and audit trails
- Handle API errors gracefully with try/catch and meaningful error responses

## Frequently asked questions

### What fields are required to create a Stripe customer?

No fields are technically required — you can call stripe.customers.create({}) with an empty object. However, you should always include at least an email for identification and reconciliation purposes.

### Can I create a customer and charge them in the same API call?

Not in a single call, but you can create a customer, then immediately create a PaymentIntent or Checkout Session with that customer ID. The two calls can happen in sequence within the same request handler.

### How many metadata fields can I add to a customer?

Up to 50 key-value pairs. Keys can be up to 40 characters and values up to 500 characters. This is enough for most use cases like storing user IDs, plan names, and internal references.

### What happens if I create a customer with the same email twice?

Stripe creates two separate customer records with different cus_ IDs. This can cause billing confusion, so always search for existing customers by email before creating new ones.

### Can I bulk-create customers via the API?

There is no bulk-create endpoint. You need to call stripe.customers.create() for each customer individually. Use Promise.all() with batches of 10-20 to stay within rate limits (100 requests/second).

### What if I need help automating customer creation for a complex signup flow?

For multi-step signup flows with payment method collection, trial periods, and subscription creation, the RapidDev team can help build a production-ready onboarding pipeline integrated with Stripe.

---

Source: https://www.rapidevelopers.com/stripe-guide/how-to-create-a-stripe-customer-programmatically
© RapidDev — https://www.rapidevelopers.com/stripe-guide/how-to-create-a-stripe-customer-programmatically
