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

# JavaScript SDK

> Install @maqetin/sdk-js, send events from the browser or Node with a public key, and send transactional email from Node with a secret key.

One package sends events in from the browser or Node, and sends transactional email from your server. This page describes version 0.2.0 and the identity-token options that come after it; the source and every release are on [GitHub](https://github.com/Maqetin/maqetin-js).

| Entry | Runs in | Key | What it does |
| - | - | - | - |
| `@maqetin/sdk-js` | Browser, Node | Public key, `mq_live_…` | `identify`, `track` (data in) |
| `@maqetin/sdk-js/server` | Node only | Secret key, `mq_sec_…` | `messages.send` (transactional messages out) |

Both entries have the same version. A web bundle that imports the main entry never holds the server entry.

## Send events

**1. Install**

```sh theme={null}
npm install @maqetin/sdk-js
```

**2. Create the client**

Pass your public key. The client refuses a secret key.

```ts theme={null}
import { MaqetinClient } from '@maqetin/sdk-js';

const mq = new MaqetinClient({
  publicKey: 'mq_live_…',
  onError: (err) => console.warn(err.kind, err.status, err.error, err.at),
});
```

**3. Identify and track**

Call `identify` when you know who the person is, and `track` when something happens. Name events `object.action` in lower case; [Events](https://docs.maqetin.com/data/events.md) lists the fields each call takes.

```ts theme={null}
mq.identify('u_42', { email: 'ada@example.com', firstName: 'Ada' });
mq.track('checkout.completed', { total: 12.5 });
```

**4. Forget the person on sign-out**

Call `reset()` when someone logs out. It forgets the person and starts a new anonymous id.

```ts theme={null}
async function logout() {
  await signOut();
  mq.reset();
}
```

Both entries are ES modules. Node 22.12 or later runs them, and a CommonJS project loads them with `require()` on that version. Browsers need nothing extra.

> [!WARNING]
>
> The SDK keeps the identified person, and the anonymous id their earlier visits are linked to, in the browser's storage, so they stay identified after a page load. Without `reset()`, the next person on the same browser is tracked as the previous one: their events go on the previous profile, and can start journeys that email the previous person.

## Identity token

When your workspace's identity verification is on, a call that names a person needs a token your server signs for that person. Give the SDK the token and it sends it for you. [Identity verification](https://docs.maqetin.com/data/identity-verification.md) shows how to sign one.

```ts theme={null}
import { MaqetinClient } from '@maqetin/sdk-js';

const mq = new MaqetinClient({
  publicKey: 'mq_live_…',
  // Asked before the token expires, when there is none, and when Maqetin refuses it.
  onIdentityTokenExpiring: async ({ userId, reason }) => {
    const res = await fetch('/api/maqetin-token'); // your server signs the token
    return res.text();
  },
});

mq.identify('u_42', { email: 'ada@example.com' }, { token: tokenFromYourServer });
mq.track('checkout.completed', { total: 12.5 }); // sent with the token
```

The token options need a version of `@maqetin/sdk-js` newer than 0.2.0.

* The SDK sends the token in the `Maqetin-Identity-Token` header with each batch that names its person, never in the events. A batch holds one person's calls, or anonymous calls only.
* It keeps the token in memory only. After a page load it has the person but no token, so it asks `onIdentityTokenExpiring` before it sends that person's calls.
* It asks 60 seconds before `exp` (or at half the time left, for a shorter token), when there is none, and when the gateway refuses one. Return the token, a promise of it, or nothing and call `setIdentityToken` later.
* A refused batch is kept, in order, and sent again with the same message ids when a different token for that person arrives. After `maxRetries` more refused tokens in a row the calls are dropped and reported to `onError` with the kind `identity`. With no `onIdentityTokenExpiring`, a refused token drops its batch at once.
* `identify` with a token for another person, or a value that is not a JWT with `sub` and `exp`, is refused and reported. `reset()` forgets the token.
* A `track` with `options.userId` for another person goes without a token.

## Methods

| Method | Returns | What it does |
| - | - | - |
| `identify(userId, traits?, options?)` | `boolean` | Names the person and keeps their id for later `track` calls, also after a page load. `userId` is your own id for them. `traits` is an object: `email` must be an email address; `phone`, `firstName`, `lastName`, `plan` and `country` are strings; `createdAt` is a `Date` or an ISO date-time in UTC. `options.timestamp` is a `Date`. `options.token` is the identity token your server signed for this person. Returns `false` when the call was refused, and reports why to `onError` |
| `track(event, properties?, options?)` | `boolean` | Records that something happened. `event` is a non-empty name, `properties` an object. The event goes on the identified person, or on the anonymous visitor before `identify`. `options.userId` names another person for this call alone; `options.timestamp` is a `Date`. Returns `false` when the call was refused |
| `page(properties?, options?)` | `boolean` | Sends a `page.viewed` event for the current page. Its properties hold `path`, `url`, `title` and `referrer`, so a journey can start on a path. Your own properties sit beside those four and never replace them. `mq.page()` sends the current page; `mq.page({ section: 'pricing' })` adds your own properties |
| `setIdentityToken(token)` | `boolean` | Gives the SDK a new identity token for the identified person; calls held for them are sent again with it. Returns `false` when it was refused (no person identified, not a JWT, or a token for another person) and reports why to `onError` |
| `reset()` | `void` | Forgets the identified person and starts a new anonymous id. Call it on logout |
| `flush()` | `Promise<void>` | Sends everything queued now |
| `close()` | `Promise<void>` | Sends what is queued and stops the client. Later calls are refused and reported with the kind `closed`. Call it before a Node process exits |

Good to know:

* The client sends a page view when it starts and when a single-page app moves to a new path (`pushState`, `replaceState`, back and forward). A change of the query string or the fragment alone is not a new page. Set `autoPageViews: false` to send page views yourself with `page()`.
* The first view is sent when the client starts, so its `title` can be empty if you load the SDK in `<head>`. The `referrer` is the page the visitor came from when the site loaded; in a single-page app it stays the same between routes, because the browser does not change it.
* A call is fixed when you make it. Changing the `properties` object after `track` does not change the event.
* Queued calls are sent when the page closes or goes to the background (`pagehide` and `visibilitychange`).

## Options

| Option | Type | Default | What it does |
| - | - | - | - |
| `publicKey` | `string` | Required | The public key, `mq_live_…`. Sent only in the `Authorization` header and never reported. A secret key is refused |
| `endpoint` | `string` | `https://in.maqetin.com` | Where batches go. By default they go to `https://in.maqetin.com/v1/batch`; set it to use another host. On a web page it may also be a path on your own site, such as `/relay`. See [Send through your own domain](https://docs.maqetin.com/sdk/javascript-own-domain.md) |
| `flushAt` | `number` | `20` | Send when this many calls are queued. At most 100 |
| `flushIntervalMs` | `number` | `100` | Send whatever is queued this long after the first call |
| `maxQueueSize` | `number` | `1000` | The most calls the client queues. A call beyond it is refused and reported with the kind `queue_full` |
| `maxRetries` | `number` | `10` | Retries of one batch after a 5xx, a 429 or a network error before it is dropped and reported |
| `retryBaseMs` | `number` | `500` | The backoff base. Retry `n` waits a random time up to `min(retryMaxMs, retryBaseMs * 2^n)`, and at least the gateway's `Retry-After`, up to `retryMaxMs` |
| `retryMaxMs` | `number` | `30000` | The longest wait between two retries |
| `requestTimeoutMs` | `number` | `10000` | Gives up on a request after this long and sends it again with the same message ids, so an event is stored once |
| `autoPageViews` | `boolean` | `true` | Sends a page view when the client starts and on each new path. Web only |
| `disableAutoCollection` | `boolean` | `false` | Leaves the collected fields out of `context`. See [Privacy and device storage](https://docs.maqetin.com/sdk/javascript-privacy.md) |
| `onError` | `(err: MaqetinError) => void` | None | Receives every call the SDK drops. Without it, the SDK writes one `console.warn` for each kind of failure and its status, so a wrong key shows once for the whole run |
| `onIdentityTokenExpiring` | `(request: { userId, reason }) => unknown` | None | Asked for a new identity token for `userId`: before the current one expires, when there is none, and when the gateway refuses one. `reason` is `expiring`, `missing`, or the code the gateway refused the token with. Return the token, a promise of it, or nothing and call `setIdentityToken` later |
| `storage` | `StorageLike` | `localStorage` in a browser, memory in Node | Where the SDK keeps its ids. Pass `memoryStorage()`, exported by the package, to keep nothing on the device |
| `fetch` | `function` | None | The `fetch` to send with, for a runtime that has none of its own |

## Limits

| What | Limit |
| - | - |
| `userId` | 1 to 256 characters |
| One call | 32 KiB as JSON |
| One batch | At most 100 calls, under about 480 KB |
| Server sends | 300 a minute per key |
| Server `data` | 16 KB as JSON |
| Server `idempotencyKey` | At most 100 |

## When a call is dropped

Every dropped call is reported to `onError` as a `MaqetinError`. No message the SDK reports or writes holds the key; reason text that holds key text is dropped.

| Field | Type | What it holds |
| - | - | - |
| `kind` | `string`, always set | `rejected`: the gateway refused the batch with a 4xx. `retries_exhausted`: the batch still failed after `maxRetries`. `queue_full`: the queue held `maxQueueSize` calls. `invalid_call`: the SDK refused the call before sending it. `closed`: the call came after `close()`. `identity`: calls held for an identity token that could no longer come, after `reset()`, another person or `close()` |
| `message` | `string`, always set | What happened, in words |
| `status` | `number` | The HTTP status, when the gateway answered |
| `error` | `string` | The gateway's reason, when it gave one |
| `at` | `string[]` | Where in the batch the gateway found the problem, for a payload it refused |
| `dropped` | `number`, always set | How many calls were dropped |

The SDK refuses a call alone, and reports it to `onError`, when it holds a value JSON cannot hold (a cycle, a `BigInt`), is over 32 KiB as JSON, has a typed trait of the wrong type, or has a `timestamp` that is not a valid `Date`. The rest of its batch is sent.

| Answer | What it means | What the SDK does |
| - | - | - |
| `401` | No active key: mistyped, deleted, revoked, or a proxy that drops `Authorization` | Drops the batch and reports it. Check that the public key is right and active |
| `401` with `token_expired`, `invalid_signature`, `sub_mismatch`, `no_matching_key` or `exp_required` | The person's identity token was refused | Keeps the batch and asks for a new token; with no `onIdentityTokenExpiring`, drops it and reports it |
| `401` with `token_required` | The workspace requires an identity token for calls that name a person, and the call had none | Drops the batch and reports it. Give the SDK a token. See [Identity verification](https://docs.maqetin.com/data/identity-verification.md) |
| `400` | A call the gateway does not accept; `at` says where | Drops the batch and reports it |
| `413` | One event or the whole body is too large | Drops the batch and reports it |
| `429` | Rate limited | Retries with backoff, waiting for `Retry-After` up to `retryMaxMs`; after `maxRetries` drops and reports it |
| `5xx` | The gateway is down or failing | Retries with backoff; after `maxRetries` drops and reports it |
| Network error or timeout | No answer | Retries with the same message ids; after `maxRetries` drops and reports it |

## Send email from your server

```ts theme={null}
import { MaqetinServer } from '@maqetin/sdk-js/server';

const mq = new MaqetinServer({ secretKey: process.env.MAQETIN_SECRET_KEY });
const { messageId } = await mq.messages.send({
  channel: 'email',
  templateId: 'tpl_receipt',
  to: { userId: 'u_42' }, // or { email: 'guest@example.com' }
  from: 'Harbour Money <receipts@mail.harbour-money.example>',
  data: { order: { id: 'o_42', total: 12.5 } },
  idempotencyKey: 'order-42:receipt',
});
```

| Topic | How it works |
| - | - |
| Key | A secret key with the `messages:send` scope, chosen when the key is made. A key without it gets `403`. The client refuses a public key and refuses to run in a web page. See [API keys](https://docs.maqetin.com/workspace/api-keys.md) |
| Before you send | The workspace must be [approved to send](https://docs.maqetin.com/workspace/sending-approval.md), and `from` must be on a verified [sending domain](https://docs.maqetin.com/messaging/sending-domains.md) of the workspace |
| Where it goes | `https://api.maqetin.com/v1/public/messages`. Set `endpoint` to use another host |
| Retries | A retry after a 5xx, a 429 or a network error carries the same `Idempotency-Key`, so it never sends a second message. If you give no key, the SDK makes one |
| Errors | A 4xx is thrown at once as `MaqetinRequestError` with `status`, `code` and `message`. A 5xx, a 429 or a network error that outlasts the retries is thrown the same way. Nothing is dropped in silence, so the server entry has no `onError` and writes no warning |
| Result | `send` resolves to `{ messageId, status: 'queued' }`. [Send a message](https://docs.maqetin.com/api-reference/send-message.md) lists every answer of the API |
| Kind of message | Transactional. It ignores the contact's email opt-in, never reaches a suppressed address, and has no unsubscribe link |

### The message

| Field | Type | What it is |
| - | - | - |
| `channel` | `'email'`, required | Email is the only channel |
| `templateId` | `string`, required | The id of a template in your workspace |
| `to` | `{ userId } \| { email }`, required | A contact by your own id for them, or an address with no contact |
| `from` | `string`, required | `Name <local@domain>` or `local@domain`, on a verified sending domain of the workspace |
| `subject` | `string` | Replaces the template's subject for this message |
| `data` | `object` | Merge data for the template, at most 16 KB as JSON |
| `idempotencyKey` | `string` | Letters, digits, `_`, `.`, `:` and `-`, at most 100. The same key on a retry is the same message, sent once. Another value is thrown before anything is sent, with the code `VALIDATION_FAILED` |

### Server options

| Option | Type | Default | What it does |
| - | - | - | - |
| `secretKey` | `string` | Required | A secret key, `mq_sec_…`. Keep it on your server |
| `endpoint` | `string` | `https://api.maqetin.com` | The API host |
| `maxRetries` | `number` | `3` | Retries after the first try, on a 5xx, a 429 or a network error |
| `retryBaseMs` | `number` | `500` | The backoff base. A retry waits at least the API's `Retry-After`, up to `retryMaxMs` |
| `retryMaxMs` | `number` | `10000` | The longest wait between two retries |
| `requestTimeoutMs` | `number` | `15000` | Gives up on a request after this long and retries it under the same idempotency key |
| `fetch` | `function` | None | The `fetch` to send with |

> [card] [Privacy and device storage](https://docs.maqetin.com/sdk/javascript-privacy.md)
>
> What the SDK collects, and every read and write it makes on the device.

> [card] [Send through your own domain](https://docs.maqetin.com/sdk/javascript-own-domain.md)
>
> Keep events flowing when a blocker list names the Maqetin host.


## Related topics

- [SDKs](https://docs.maqetin.com/sdk/overview.md)
- [Privacy and device storage](https://docs.maqetin.com/sdk/javascript-privacy.md)
- [Send through your own domain](https://docs.maqetin.com/sdk/javascript-own-domain.md)
- [Send a message](https://docs.maqetin.com/api-reference/send-message.md)
- [Quickstart](https://docs.maqetin.com/quickstart.md)


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