# JavaScript client

Read published and draft content from any JavaScript runtime with @mojimoto/client, a typed wrapper around the Content Delivery API.

`@mojimoto/client` is a typed wrapper around the [Content Delivery API](/docs/api/delivery). It runs anywhere `fetch` exists: Node 18 and newer, browsers, edge runtimes, Deno and Bun. Use it on its own, or through the [Next.js](/docs/frameworks/nextjs) and [Nuxt](/docs/frameworks/nuxt) packages, which wrap it.

This page describes version 0.5.0. The client reads content. It does not write it: for that, call the [Management API](/docs/api/management).

## Install

```bash
npm i @mojimoto/client
```

## Create a client

```ts lib/cms.ts
import { createClient } from '@mojimoto/client'

export const cms = createClient({
  endpoint: 'https://mojimoto.com/api/v1',
  project: 'acme',
  token: process.env.MOJIMOTO_TOKEN!,
})
```

Create one client per project and reuse it. `createClient` throws an `Error` if `endpoint`, `project` or `token` is empty.

| Option | Type | Description |
| --- | --- | --- |
| `endpoint` | `string` | Required. The API base URL, without the project. |
| `project` | `string` | Required. The project slug. |
| `token` | `string` | Required. A token with the `read` ability, such as `mjmt_your_read_token`. Sent as a Bearer token. |
| `lang` | `string` | The locale for calls that do not pass one. Without it, the API uses the project's default locale. |
| `preview` | `boolean` | Ask for drafts on every call. See [Read drafts](#read-drafts). |
| `fetch` | `typeof fetch` | Your own `fetch`, for Node older than 18 or a framework's version. |
| `headers` | `Record<string, string>` | Extra headers sent with every request. |
| `retry` | `number` or `RetryOptions` | Retry failed requests. Off by default. See [Retry failed requests](#retry-failed-requests). |

Tokens are covered in [Authentication](/docs/api/authentication). The client has five methods, and `cms.options` holds the options it was created with.

| Method | Resolves to |
| --- | --- |
| `query(options)` | One page of entries, with the totals. |
| `all(options)` | Every matching entry, as an array. |
| `first(options)` | The first matching entry, or `null`. |
| `byUid(type, uid, options)` | The entry of that content type with that UID, or `null`. |
| `byId(id, options)` | The entry with that numeric id. Throws when there is none. |

## List entries

`query` makes one request and returns the page as the API sent it.

```ts
const page = await cms.query({ type: 'post', sort: '-updated_at', perPage: 10 })
```

```json
{
  "results": [
    {
      "id": 42,
      "uid": "hello-world",
      "type": "post",
      "lang": "en-gb",
      "status": "published",
      "published_at": "2026-11-02T09:30:00+00:00",
      "updated_at": "2026-11-02T09:30:00+00:00",
      "data": { "title": "Hello world" }
    }
  ],
  "page": 1,
  "per_page": 10,
  "total_results": 24,
  "total_pages": 3,
  "lang": "en-gb",
  "ref": "published"
}
```

| Option | Type | Description |
| --- | --- | --- |
| `type` | `string` | Only entries of this content type. |
| `uid` | `string` | Only the entry with this UID. |
| `lang` | `string` | The locale, in place of the client's `lang`. |
| `page` | `number` | The page to return, starting at 1. |
| `perPage` | `number` | Entries per page. The API defaults to 20 and stops at 100. |
| `sort` | `string` | `id`, `uid`, `created_at` or `updated_at`, or a field as `fields.price`. Put `-` in front for descending. The default is `id`. Sorting by a field needs `type`. |
| `depth` | `1`, `2` or `3` | How many levels of linked entries to include. The default is 1. |
| `preview` | `boolean` | Ask for drafts on this call. |
| `signal` | `AbortSignal` | Cancels the request. |

Two more methods take the same options:

```ts
// Every page, 100 entries at a time, as one array
const posts = await cms.all({ type: 'post' })

// The first match, or null
const latest = await cms.first({ type: 'post', sort: '-updated_at' })
```

## Filter by a field

The client has options for `type` and `uid` only. The API can also filter on field values and return only the fields you name, but the client has no options for either yet. Until it does, call the endpoint with `fetch` and use the client's types:

```ts
import type { MojimotoListResponse } from '@mojimoto/client'

const params = new URLSearchParams({
  type: 'post',
  'fields.category': 'news',
  select: 'fields.title,fields.category',
})

const response = await fetch(`https://mojimoto.com/api/v1/acme/documents?${params}`, {
  headers: { Authorization: `Bearer ${process.env.MOJIMOTO_TOKEN}` },
})

const posts: MojimotoListResponse = await response.json()
```

Every filter is listed in the [Delivery API reference](/docs/api/delivery).

## Fetch one entry

```ts
// By content type and UID. Returns null when there is no match.
const home = await cms.byUid('page', 'home', { depth: 2 })

// By numeric id. Throws a MojimotoError with status 404 when there is no match.
const entry = await cms.byId(42)
```

Both take `lang`, `depth`, `preview` and `signal` as a last argument.

## Linked entries and depth

A `reference` field arrives as the linked entry itself, and a `references` field as an array of them. `depth` sets how many levels are included. Past that, a link is only `{ id, type, uid }`, so check for `data` before you read it. The `MojiReference` type describes both forms. See [Links](/docs/concepts/links).

## Read drafts

Pass `preview: true`, on the client or on one call, to get the newest version of each entry, published or not. The token needs the `preview` ability.

```ts
const draft = await cms.byUid('page', 'home', { preview: true })
```

> **Warning:** If the token cannot preview, the API does not fail. It answers with published content. On a list, `ref` in the response says which you got: `"preview"` or `"published"`.

See [Preview](/docs/concepts/preview) and the [Preview API](/docs/api/preview).

## Retry failed requests

```ts
const cms = createClient({ endpoint, project, token, retry: 3 })
```

A number is the most attempts to make, counting the first. With retries on, the client tries again after a network error, a 429 or a 5xx, and never after any other 4xx. It waits for the `Retry-After` header when there is one. For more control pass an object:

| Option | Default | Description |
| --- | --- | --- |
| `attempts` | 3 | The most attempts, counting the first. |
| `backoffMs` | 300 | The first wait in milliseconds. It doubles each time. |
| `maxBackoffMs` | 5000 | The longest single wait. |

## Errors

Any response that is not 2xx throws a `MojimotoError`.

```ts
import { MojimotoError } from '@mojimoto/client'

try {
  await cms.byId(999999)
} catch (error) {
  if (error instanceof MojimotoError) {
    error.status // 404
    error.body // the response body, parsed as JSON when it can be
    error.url // the URL that was requested
  }
}
```

The message is `Mojimoto request failed (404)`. For API errors `body` is `{ message: string }`, for example `{ "message": "Invalid API token." }` with a 401. A token for another project, or one without the `read` ability, is a 403. A network failure throws whatever `fetch` threw, not a `MojimotoError`. Every status is on the [Errors](/docs/api/errors) page.

## Types

| Type | What it is |
| --- | --- |
| `MojimotoClient`, `MojimotoClientOptions` | The client and its options. |
| `QueryOptions`, `FetchOptions`, `RetryOptions` | The options for list calls, single entry calls and retries. |
| `MojimotoDocument<Type, Data>` | One entry. `data` is your fields. |
| `MojimotoListResponse<Document>` | A page of entries with its totals. |
| `MojiReference<Document>` | A `reference` field: the linked entry, a `{ id, type, uid }` link, or `null`. |
| `MojimotoBlock<Type, Data>` | One block of a `blocks` field: `{ id, type, data }`. |
| `MojimotoSlice` | A `MojimotoDocument` or a `MojimotoBlock`. |
| `MojiRichText`, `MojiLink` | A `rich_text` field and a link inside one. See [Rich text](/docs/frameworks/rich-text). |
| `MojiLocation` | A `location` field: `{ lat, lon }` or `null`. |
| `MojimotoWebhookPayload`, `VerifyWebhookOptions` | See [Verify a webhook](#verify-a-webhook). |

> **Warning:** `MojiMedia` is exported as `string | null`, which is out of date. The API delivers a `media` field as an object: `{ id, url, alt, width, height, content_type, fit }`, or `null`. Use `MojimotoMedia` from your generated types, or write that shape yourself.

## Use generated types

Every method takes the type of the entry it returns. Pass the whole document type, not only its fields. [Generated types](/docs/tools/generated-types) give you the fields of each content type:

```ts
import type { MojimotoDocument } from '@mojimoto/client'
import type { PostData } from './mojimoto.generated'

type Post = MojimotoDocument<'post', PostData>

const post = await cms.byUid<Post>('post', 'hello-world')

post?.data.title // typed as your model defines it
```

Generated types leave a rich text field as `unknown`. Cast it to `MojiRichText` before you render it.

## Verify a webhook

`verifyWebhookSignature` checks that a webhook request came from Mojimoto. It uses Web Crypto, so it runs in Node and in edge runtimes, and it resolves to `true` or `false`.

```ts
import { verifyWebhookSignature, type MojimotoWebhookPayload } from '@mojimoto/client'

export async function POST(request: Request) {
  const body = await request.text()

  const signed = await verifyWebhookSignature({
    body,
    signature: request.headers.get('x-mojimoto-signature'),
    secret: process.env.MOJIMOTO_WEBHOOK_SECRET!,
  })

  if (!signed) {
    return new Response('Bad signature', { status: 401 })
  }

  const payload: MojimotoWebhookPayload = JSON.parse(body)

  return Response.json({ received: payload.event })
}
```

Pass the body exactly as it arrived, before any JSON parsing. `payload.document` is the whole entry on `document.published`. On `document.unpublished` and `document.deleted` it holds only the entry's `id`, `type` and `uid`, although the type says otherwise. See [Webhooks](/docs/concepts/webhooks).
