# Signed-in buyers

Use your shop's existing login. OrbCart keeps no accounts; it trusts your ID tokens.

Buyers sign in with **your** identity system: Better Auth, Auth0, Clerk, Keycloak,
your own. OrbCart checks the ID token and keeps only its issuer and subject. No
passwords, no profiles, no second user database.

What signing in gives the buyer:

- **One Cart on every device.** Lines from a guest Cart join their own Cart.
- **Their own prices.** Your `offers` function sees `context.buyer`.
- **Their Orders,** including earlier guest Orders to the same verified email.

## 1. Trust your identity system

```ts title="src/worker.ts" worker
export default defineCommerce({
  channels,
  offers,
  identity: {
    issuers: [{ issuer: "https://auth.example.com", audience: "shop" }],
  },
});
```

OrbCart finds the keys through OpenID discovery. If your issuer has no discovery
document, name the key set yourself:

```ts worker value="Issuer"
{ issuer: "https://shop.example.com", audience: "shop", jwks: "https://shop.example.com/api/auth/jwks" }
```

## 2. Send the token from the storefront

Give `createCommerce` a function that returns the current ID token, or `undefined`
while nobody is signed in. It is asked before every request:

```ts
const commerce = createCommerce({
  url,
  key,
  buyer: () => auth.getIdToken(),
});
```

When OrbCart rejects a token, it asks once more with that token as `refused` and
retries the request with the fresh one. If your identity system caches tokens, renew
there:

```ts
const commerce = createCommerce({
  url,
  key,
  buyer: (asked) => auth.getIdToken({ forceRefresh: asked?.refused !== undefined }),
});
```

## 3. Claim the Cart after sign-in

Right after the buyer signs in, call `identify()`. Continue with the Cart it returns:

```ts
const { access, merged } = await cart.identify();

saveCartToken(access.token);
if (merged) showToast("We added the items from your other device.");
```

`access` is usually the same Cart. It is a different one when the buyer already
had a Cart elsewhere that took over these Lines.

## Show the buyer's Orders

```ts
const page = await commerce.orders();
const older = page.next ? await commerce.orders({ after: page.next }) : undefined;
```

Newest first, in this Channel only.

## Prices per customer group

```ts worker
export const offers: OffersContract = async (lines, { buyer, currency }) => {
  const group = buyer ? await crm.groupOf(buyer.subject) : "retail";
  return pricing.offers(lines, { group, currency });
};
```

`buyer` is `{ issuer, subject }`. It is never a profile, so your CRM stays the
source of names and groups.

## Sign-in inside the React checkout

`@orbcart/client/better-auth` connects Better Auth to both the checkout and the client.
A known email address is offered a sign-in right in the checkout:

```tsx
import { betterAuthIdentity } from "@orbcart/client/better-auth";

const identity = betterAuthIdentity({
  client: authClient,
  knows: (email) =>
    fetch("/api/has-account", { method: "POST", body: email }).then((r) => r.json()),
});

const commerce = createCommerce({ url, key, buyer: identity.buyer });

<Checkout
  cart={cart}
  locale="en-GB"
  identity={identity}
  onSignedIn={(access) => setCart(access)}
/>;
```

Your Better Auth server needs the `emailOTP` and `jwt` plugins, and
`emailAndPassword` when you offer `methods: ["password", "code"]`. Rate-limit the
`knows` endpoint and protect it with a bot check, such as Turnstile.

OrbCommerce's own shopper sign-in, `shopperAuth` from `@orbcommerce/auth/shopper`,
has all three. Shoppers sign up and sign in with an email address and a password
of at least eight characters, and change it while signed in. A forgotten password
is reset with a code by email, and the same kind of code signs in without the
password. `sendCode` receives each code with its `purpose` (`sign-in`,
`confirm-address` or `reset-password`), so the email can say what it is for.
Throw from `sendCode` when your mail provider refuses a code. A sign-in code,
where codes may also sign up, and a sign-up's code are sent to any address, so
their request then answers `503` with the problem code `code_not_sent` and
`Retry-After: 60`; a retry sends a fresh code. A reset code and a sign-in code
where only accounts sign in go only to an address with an account, so their
request answers as for an address without one, and the failure reaches only
your logs, without the address.

`shopperAuth` requires a Cloudflare rate-limit binding as `attempts`. It rations
every password check or hash and every code sent or checked, per route and per
network (an IPv6 client's /64). Keys are hashed, never raw addresses. Choose the
binding's limit for your traffic: shoppers behind one mobile carrier's address
share it, and Cloudflare counts attempts per location, not globally. Your `knows`
endpoint is yours to ration: `withinAttempts(request, env.SIGN_IN_LIMITER)` from
`@orbcommerce/auth/shopper` counts it the same way. These limits guard the HTTP
handler; call it rather than the direct `auth.api` methods for passwords and codes.

A sign-up answers alike for a new and a known address and opens no session. Sign
the shopper in with the password afterwards; if the address already had an account
with another password, that sign-in fails like any wrong password. An emailed code
gets the address's owner in.

A password sign-up never verifies the address, and OrbCart shows a buyer's guest
Orders only for a verified one. A code verifies it: signing in or resetting the
password with one, or confirming a new account with `confirmAddress: true`, which
mails a code on sign-up and expects your sign-up page to ask for it. Signing in
by code to an address that never proved itself drops the password set before the
proof, so a stranger who signed up with someone else's address cannot keep it.

## Good to know

- **Signing out ends the Cart on that device.** A buyer's Cart only opens next to their token. The next `add()` starts a fresh guest Cart.
- **Someone else's Cart on a shared computer?** `identify()` notices and gives the buyer their own.
- **Discount limits per buyer** count signed-in buyers by identity and guests by email. [Discounts →](/docs/shop/discounts)

[Build the Cart →](/docs/shop/carts)