First, create a new Nuxt application, which sets up a basic Nuxt application for you. To create a project, run the following command:
npx nuxi init nuxt-app
Then enter inside the project directory, install the dependencies, and start the development server:
cd nuxt-appnpm run dev
We also need the @datocms/cda-client
package, which provides a series of convenient utilities for making calls to the Content Delivery API:
npm i --save @datocms/cda-client
Nuxt comes with a set of methods for fetching data from any API. The best way to retrieve data from Dato's GraphQL API is building a custom composable relying on useFetch
:
import { buildRequestInit } from '@datocms/cda-client';export function useQuery(query, options) {const config = useRuntimeConfig();const optionsWithToken = {...options,token: config.datocmsApiToken,};return useFetch('https://graphql.datocms.com/', {...buildRequestInit(query, optionsWithToken),key: hash([query, optionsWithToken]),transform: ({ data, errors }) => {if (errors)throw new Error(`Something went wrong while executing the query: ${JSON.stringify(errors)}`,);return data;},});}
The DatoCMS API token can be stored in an environment variable and provided to Nuxt application via the nuxt.config.ts
file:
export default defineNuxtConfig({runtimeConfig: {// set by NUXT_DATOCMS_API_TOKEN env variabledatocmsApiToken: '',}})
To create an API token for a DatoCMS project, go in the "Settings > API Tokens" section, making sure you only give it permission to access the (read-only) Content Delivery API.
Finally, you'll need to set up a .env
file to store the DatoCMS token:
DATO_CMS_TOKEN=<THE_TOKEN_YOU_JUST_CREATED>
You can then use the composable in your pages and layouts:
<script setup>const QUERY = `query {blog {title}}`;const { data, error } = useQuery(QUERY);</script><template><p v-if="error">Something bad happened!</p><p v-else>Data: <code>{{ JSON.stringify(data) }}</code></p></template>
The QUERY
is the GraphQL query, and of course, it depends on the models available in your specific DatoCMS project. You can learn everything you need regarding how to build GraphQL queries on our Content Delivery API documentation.