# Nuxt

Add the @mojimoto/nuxt module for a configured client, composables that fetch on the server and auto-imported rich text components.

`@mojimoto/nuxt` is a Nuxt module. It creates a [client](/docs/frameworks/javascript) from your config, adds three auto-imported composables that fetch on the server and hydrate in the browser, and registers the [Vue components](/docs/frameworks/vue) globally.

It declares support for Nuxt 3.0 and newer. This page describes version 0.2.3.

## Install

```bash
npm i @mojimoto/nuxt
```

```ts nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@mojimoto/nuxt'],

  mojimoto: {
    endpoint: 'https://mojimoto.com/api/v1',
    project: 'acme',
  },
})
```

```env .env
MOJIMOTO_TOKEN=mjmt_your_read_token
```

## Module options

Options go under the `mojimoto` key. Three of them fall back to an environment variable.

| Option | Falls back to | Description |
| --- | --- | --- |
| `endpoint` | `MOJIMOTO_ENDPOINT` | The API base URL, without the project. |
| `project` | `MOJIMOTO_PROJECT` | The project slug. |
| `token` | `MOJIMOTO_TOKEN` | A token with the `read` ability. |
| `lang` | | The locale for calls that do not pass one. |
| `preview` | | Ask for drafts on every call. Off by default. |
| `components` | | Register the components globally. On by default. |

Two things to know:

- The values are stored in `runtimeConfig.public.mojimoto`, so the token is sent to the browser. Use a token with only the `read` ability, never one that can write.
- The module reads the environment variables when Nuxt builds, or when it starts in development. A built app keeps the values it was built with. To change one without rebuilding, set Nuxt's own runtime variable, such as `NUXT_PUBLIC_MOJIMOTO_TOKEN`.

## Fetch an entry in a page

```vue pages/blog/[uid].vue
<script setup lang="ts">
import type { MojimotoDocument, MojiRichText } from '@mojimoto/client'

type Media = { url: string; alt: string | null }

type Post = MojimotoDocument<'post', { title: string; cover: Media | null; body: MojiRichText }>

const route = useRoute()

const { data: post } = await useMojiDocument<Post>('post', String(route.params.uid))

if (!post.value) {
  throw createError({ statusCode: 404, statusMessage: 'Post not found' })
}
</script>

<template>
  <article v-if="post">
    <h1>{{ post.data.title }}</h1>
    <MojiImage :field="post.data.cover?.url" :alt="post.data.cover?.alt ?? ''" />
    <MojiRichText :field="post.data.body" />
  </article>
</template>
```

The entry is fetched while the page renders on the server and travels to the browser in Nuxt's payload, so it is not fetched twice.

To import types as above, add the client to your own dependencies with `npm i @mojimoto/client`. [Generated types](/docs/tools/generated-types) can replace the ones written by hand here.

## Composables

All three are auto-imported.

| Composable | What it does |
| --- | --- |
| `useMojiDocument(type, uid, options, key)` | Fetches one entry by content type and UID. `data` is the entry, or `null` when there is none. The options are `lang`, `preview` and `depth`. |
| `useMojiQuery(options, key)` | Fetches one page of a list. `data` is the array of entries. The options are those of the client's [query](/docs/frameworks/javascript#list-entries). |
| `useMojimoto()` | Returns the client itself. |

`useMojiDocument` and `useMojiQuery` wrap Nuxt's `useAsyncData` and return what it returns: `data`, `error`, `status`, `refresh` and the rest.

```ts
const { data: home } = await useMojiDocument('page', 'home', { depth: 2 })

const { data: posts } = await useMojiQuery({ type: 'post', sort: '-updated_at', perPage: 12 })
```

Each call gets a cache key built from its arguments. Pass your own as the last argument when you want to refresh or share the data by name:

```ts
const { data: posts } = await useMojiQuery({ type: 'post' }, 'all-posts')
```

`useMojiQuery` gives you the entries but not the totals. For paging, call the client inside `useAsyncData`:

```ts
const cms = useMojimoto()

const { data: page } = await useAsyncData('posts-page-2', () => cms.query({ type: 'post', page: 2, perPage: 10 }))

// page.value?.results, page.value?.total_pages
```

> **Note:** `@mojimoto/vue` exports composables with the same two names. Those fetch in the browser only. In a Nuxt app the auto-imported ones are the module's.

## Components

`MojiRichText`, `MojiText`, `MojiImage` and `MojiLink` are registered globally, so you can use them in any template with no import. Their props are on the [Vue components](/docs/frameworks/vue) page. Set `components: false` to register none of them and import what you need from `@mojimoto/vue`.

The module has no option for a link resolver. Pass one to the component:

```vue
<MojiRichText :field="post.data.body" :link-resolver="(link) => `/${link.uid}`" />
```

## Preview drafts

Turn on the `preview` option and every call asks for the newest version of each entry, published or not. Do that for a staging build, not for the live site:

```ts nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@mojimoto/nuxt'],

  mojimoto: {
    endpoint: 'https://mojimoto.com/api/v1',
    project: 'acme',
    preview: process.env.MOJIMOTO_PREVIEW === 'true',
  },
})
```

`MOJIMOTO_PREVIEW` is a variable of your own here, read when Nuxt builds. One call can also ask for drafts by itself:

```ts
const { data: home } = await useMojiDocument('page', 'home', { preview: true })
```

Two things to know:

- The token needs the `preview` ability. Without it the API returns published content and no error.
- That token is in the public runtime config, so anyone who loads the site can read your drafts with it. Give the staging build its own token, and keep a token with only `read` on the live site.

To open the staging site from the editor, set the project's **Preview base URL** and the content type's **Preview path**. See [Preview](/docs/concepts/preview).

## Use the client directly

`useMojimoto()` returns the same client as [createClient](/docs/frameworks/javascript), for anything the composables do not cover. It is also on the Nuxt app as `$mojimoto`.

```ts
const cms = useMojimoto()

const authors = await cms.all({ type: 'author' })
```

A call like this, outside `useAsyncData`, runs on the server and again in the browser.
