Nuxt 3 comes with a set of methods for fetching data from any API.
It's easy to retrieve data from Dato's GraphQL API with the useFetch
composable:
<script setup>const QUERY = `query {blog {seo: _seoMetaTags {attributescontenttag}}}`;const runtimeConfig = useRuntimeConfig();const { data, error } = await useFetch('https://graphql.datocms.com', {method: 'POST',headers: {Authorization: `Bearer ${runtimeConfig.public.datoCmsToken}`,},body: {query: QUERY,},transform: ({ data, errors }) => {if(errors) throw new errors;return data;},});</script><template><p v-if="error">Something bad happened!</p><p v-else>Data: <code>{{ data }}</code></p></template>
datoCmsToken
can be stored in an environment variable and provided to Nuxt application via the nuxt.config.ts
file:
export default defineNuxtConfig({runtimeConfig: {public: {datoCmsToken: process.env.DATO_CMS_TOKEN,}}})
During development, Nuxt supports .env
files out of the box.
The approach just described covers simple cases: for a slightly mode advanced tour, in this tutorial we'll create a Nuxt application fetching data via a custom composable based on useFetch
.
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
First, you need 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.
Then, you'll need to set up a .env
file to store the DatoCMS token:
DATO_CMS_TOKEN=THE_TOKEN_YOU_JUST_CREATED
Next, create a composables/useGraphqlQuery.js
— that is the function that will make the actual call to the DatoCMS GraphQL API:
export default (options) => {const { query, variables = {} } = options;const runtimeConfig = useRuntimeConfig();const key = JSON.stringify(options);return useFetch('https://graphql.datocms.com', {key,method: 'POST',headers: {Authorization: `Bearer ${runtimeConfig.public.datoCmsToken}`,},body: {query,variables,},transform: ({ data, errors }) => {if(errors) throw new errors;return data;},});};
Now you can use the composable to retrieve data from DatoCMS:
<script setup>const QUERY = `query {blog {seo: _seoMetaTags {attributescontenttag}}}`;const { data, error } = await useGraphqlQuery({ query: QUERY });</script><template><p v-if="error">Something bad happened!</p><p v-else>Data: <code>{{ 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.