> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stateset.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Customers Quickstart

> Create and reuse a customer, update contact details, add a shipping address, and link an order using the embedded Node.js engine.

Use **`@stateset/embedded` 1.39.0** to create a customer and reuse its returned ID throughout a
local workflow. This example runs in a fresh in-memory database and needs no API key, payment
provider, or subscription setup.

## Prerequisites

Use Node.js **20.20.0+** and npm **10+**. In a new directory:

```bash theme={null}
mkdir stateset-customers-example
cd stateset-customers-example
npm init -y
npm install @stateset/embedded@1.39.0
```

See [SDK installation](https://docs.stateset.com/guides/sdk-installation.md) if the native module cannot load.

## Run the complete example

Save this as `customers-demo.mjs`:

```javascript theme={null}
import assert from 'node:assert/strict';
import { Commerce } from '@stateset/embedded';

const commerce = new Commerce(':memory:');
const input = {
  email: 'ada@example.com',
  firstName: 'Ada',
  lastName: 'Lovelace',
  acceptsMarketing: false,
};
const customer = await commerce.customers.findOrCreate(input);
assert.equal(customer.status, 'active');
assert.equal(customer.acceptsMarketing, false);
console.log(`Customer: ${customer.email}, ${customer.status}`);

const existing = await commerce.customers.findOrCreate({
  ...input, firstName: 'Changed name',
});
assert.equal(existing.id, customer.id);
assert.equal(existing.firstName, 'Ada');
assert.equal(await commerce.customers.count(), 1);
console.log('Email lookup reused the customer without changing the name');

await assert.rejects(
  () => commerce.customers.create(input),
  { code: 'CONFLICT' },
);
assert.equal(await commerce.customers.count(), 1);
console.log('Duplicate create rejected; customer count is still 1');

await commerce.customers.update(customer.id, {
  phone: '+12025550123',
  tags: ['wholesale'],
});
const saved = await commerce.customers.get(customer.id);
assert.equal(saved.phone, '+12025550123');
assert.deepEqual(saved.tags, ['wholesale']);
assert.equal(saved.acceptsMarketing, false);
console.log('Contact update persisted; marketing preference is unchanged');

const address = await commerce.customers.addAddress({
  customerId: customer.id,
  addressType: 'shipping',
  firstName: 'Ada',
  lastName: 'Lovelace',
  line1: '123 Example Street',
  city: 'Portland',
  state: 'OR',
  postalCode: '97205',
  country: 'US',
  isDefault: true,
});
const addresses = await commerce.customers.getAddresses(customer.id);
assert.equal(addresses.length, 1);
assert.equal(addresses[0].id, address.id);
assert.equal(addresses[0].isDefault, true);
console.log(`Default address: ${address.addressType}, ${address.country}`);

const order = await commerce.orders.createExact({
  customerId: customer.id,
  currency: 'USD',
  items: [{ sku: 'MUG-001', name: 'Ceramic mug', quantity: 1, unitPrice: '12.50' }],
});
assert.equal(order.customerId, customer.id);
assert.equal(order.totalAmountExact, '12.50');
assert.equal(await commerce.customers.getByEmail('missing@example.com'), null);
console.log(`Linked order: ${order.totalAmountExact} ${order.currency}`);
console.log('Missing email lookup returned null');
```

```bash theme={null}
node customers-demo.mjs
```

**Success:** all assertions pass and you see:

```text theme={null}
Customer: ada@example.com, active
Email lookup reused the customer without changing the name
Duplicate create rejected; customer count is still 1
Contact update persisted; marketing preference is unchanged
Default address: shipping, US
Linked order: 12.50 USD
Missing email lookup returned null
```

## Choose create, lookup, or update

| Intent | Node method | Result to inspect |
| - | - | - |
| Create a new customer | `customers.create(input)` | New customer; the duplicate email above produces `CONFLICT` |
| Reuse a customer by email, or create it | `customers.findOrCreate(input)` | Existing or new customer; existing profile fields are not updated by the replay above |
| Read by stable ID | `customers.get(id)` | Customer or `null` |
| Look up an email | `customers.getByEmail(email)` | Customer or `null` |
| Change an existing record | `customers.update(id, changes)` | Updated customer |
| Add a separate address record | `customers.addAddress(input)` | Address with its own ID and `customerId` |
| Read the customer's addresses | `customers.getAddresses(customerId)` | Array of address records |

`findOrCreate` is useful when the exact email is already known. It is not a profile merge or a
substitute for `update`. This walkthrough verifies repeated calls using the same email; it does
not establish alias matching, normalization rules, or concurrent import behavior.

Save the returned customer ID as the relationship key for orders. If you integrate an external
CRM or payment provider, maintain its customer ID separately and reconcile it explicitly. The
local record does not create a provider customer or start recurring billing.

## Addresses and preferences

The customer input uses `firstName`, `lastName`, and `acceptsMarketing`. Addresses are created
with a separate method using `line1`, `postalCode`, and `country`; do not pass a nested REST-style
`customer` object to this binding.

The example preserves `acceptsMarketing: false` during a contact update. Set marketing
preferences from your application's recorded choice, rather than changing them as a side effect
of an import or checkout.

Adding a default customer shipping address stores that address on the customer. The order above
only verifies its `customerId`; it does not establish that an address was copied onto the order,
that postage was bought, or that any goods shipped.

## Troubleshooting

| Symptom | Check or next step |
| - | - |
| `CONFLICT` on a repeated create | Look up the existing email, then decide whether to reuse or update that customer |
| Changed name is ignored by `findOrCreate` | Use `update` with the saved customer ID for intentional profile changes |
| Lookup returns `null` | Confirm the ID or email and that both calls use the same database |
| Address is absent from the customer object | Read `getAddresses(customer.id)`; addresses are separate records |
| Unexpected duplicate address | Persist the returned address ID; the example does not establish replay protection for `addAddress` |
| Records disappear after exit | `:memory:` is temporary; use the persisted quickstart for a file-backed database |

## Next steps

* [Orders quickstart](https://docs.stateset.com/guides/orders-quickstart.md): add stock checks, reservation, and cancellation.
* [Payments and refunds](https://docs.stateset.com/guides/payments-quickstart.md): explore local payment records and retry identity.
* [Integration testing](https://docs.stateset.com/guides/api-testing.md): put assertions into an automated test suite.
* [Persisted quickstart](https://docs.stateset.com/stateset-icommerce/stateset-icommerce-quickstart.md): verify the same record from a second process.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.