# JavaScript SDK

> The client the API publishes at /sdk.js and /sdk.mjs, generated from the specification itself. How to load it in the browser and in Node, the methods by topic, how to pass parameters and body, error handling and the client options.

The API publishes a **JavaScript SDK** generated from its own OpenAPI specification. It covers every operation, sends the headers for you, unwraps the response envelope and turns errors into exceptions.

| File | Use |
|---|---|
| [`/sdk.js`](https://api.memberfy.net/sdk.js) | UMD: `<script src>` (exposes `Memberfy`) or `require()` in Node |
| [`/sdk.mjs`](https://api.memberfy.net/sdk.mjs) | ESM: `import { createClient } from '…/sdk.mjs'` |

## Getting started in the browser

```html
<script src="https://api.memberfy.net/sdk.js"></script>
<script>
  const api = Memberfy.createClient({ baseUrl: 'https://api.memberfy.net' });

  const session = await api.auth.login({ email, password });
  api.setToken(session.token).setCommunity(communityId);

  const me = await api.auth.getMe();
</script>
```

**Always pass the `baseUrl` with `https://`.**

## Getting started in Node

Download the file into your project and import it locally (Node 18 or newer, which already has `fetch`):

```bash
curl -s https://api.memberfy.net/sdk.mjs -o memberfy-sdk.mjs
```

```js
import { createClient } from './memberfy-sdk.mjs';

const api = createClient({ baseUrl: 'https://api.memberfy.net' });
const session = await api.auth.login({ email: process.env.MEMBERFY_EMAIL, password: process.env.MEMBERFY_PASSWORD });
api.setToken(session.token).setCommunity(process.env.MEMBERFY_COMMUNITY_ID);
```

Download it again whenever you want to update.

## What it does for you

| | |
|---|---|
| **Headers** | `Authorization`, `X-CommunityId`, `X-ProfileId` and `Accept-Language`, from `setToken`, `setCommunity`, `setProfile` and `setLanguage` |
| **Envelope** | Returns `data` directly; lists return `{ data, pagination }` |
| **Errors** | Throws `MemberfyError`, with `.status`, `.body` and `.errors` |
| **Session** | `onUnauthorized` is called on a `401`, so you can sign in again |

## The methods

Methods are grouped by topic (the same topics as the [reference](/api/referencia)): `api.auth`, `api.products`, `api.subscriptions`, `api.coupons`, `api.sectionsSpaces`, `api.events`… The method name comes from the operation's `operationId`: `api.products.postCommunitiesByCommunityIdProducts`, `api.profiles.getList`, `api.auth.login`.

Some names still carry `CommunitiesByCommunityId` from when the route had the community in the path. Since October 6, 2026 no route carries the community in the path, but the names stayed, so nothing breaks in your code. The community always goes through `setCommunity`. See [X-CommunityId](/api/x-community-id#the-paths-that-changed).

Each endpoint's page in the reference shows its `operationId`.

## Parameters and body

Path and query parameters go by name; **everything else becomes the body**:

```js
api.setCommunity(communityId); // the community goes in the X-CommunityId header

await api.products.putCommunitiesByCommunityIdProductsById({
  id: productId,               // goes into the path
  type: 'SUBSCRIPTION',        // body
  title: 'Student · Monthly',  // body
  price: 49,                   // body
  billingInterval: 'MONTHLY',  // body
  allowedPaymentMethods: ['PIX', 'CREDIT_CARD', 'BOLETO'],
});
```

You can also split them: `{ id, body: { … } }`. **Don't pass `communityId` in the arguments**: since it's no longer a path parameter, it would go into the body. Other per-call options: `headers` (extra headers), `query` (additional query parameters) and `signal` (an `AbortController`).

For any route, there's `api.request({ httpMethod, path, pathParams, queryParams, hasBody }, args)`.

## Handling errors

```js
try {
  await api.coupons.postCommunitiesByCommunityIdCouponsValidate({ code: 'LAUNCH20' });
} catch (error) {
  if (error.name === 'MemberfyError') {
    console.log(error.status);  // 400
    console.log(error.errors);  // [{ param: 'code', message: 'Coupon has expired' }]
  }
}
```

## Client options

| Option | What for |
|---|---|
| `baseUrl` | The API address. Use `https://api.memberfy.net` |
| `token`, `communityId`, `profileId`, `language` | Initial header values |
| `raw: true` | Returns the raw body, with the envelope |
| `onUnauthorized` | A function called on a `401` |
| `fetch` | A `fetch` implementation, for environments without a native one |

## Always current

The SDK is generated each time it's served, from the API's routes. Downloading it again means updating it.

## For AI

For an assistant to generate correct calls, give it the [`/docs.txt`](https://api.memberfy.net/docs.txt) as well: the SDK says **how** to call; `/docs.txt` says **what** to send.

## Related

- [Authentication](/api/autenticacao)
- [Responses and errors](/api/respostas-e-erros)
- [API Reference](/api/referencia)
