While you're working on a Nuxt website, it may be useful to include draft contents from DatoCMS: this way, you can preview how the site will look in the end before actually publishing any record.
To do that, you need to tell our GraphQL API to include draft records when executing the queries.
useGraphqlQuery
Start by upgrading the composable we created for fetching data from DatoCMS GraphQL API, so that you can specify when you want to include draft records:
export default (options) => {const { query, variables = {}, includeDrafts = false } = options;const runtimeConfig = useRuntimeConfig();const key = JSON.stringify(options);return useFetch('https://graphql.datocms.com', {key,method: 'POST',headers: {Authorization: `Bearer ${runtimeConfig.public.datoCmsToken}`,...(includeDrafts && { 'X-Include-Drafts': 'true'}),},body: {query,variables,},transform: ({ data, errors }) => {if(errors) throw new errors;return data;},});};
With this new version of the composable, you can decide to include draft records depending on the context.
For example, if you want a preview of the contents while working on the site in development mode, we can do as follow.
First, change the nuxt.config.ts
file to expose the current environment:
// In the nuxt.config.tsexport default defineNuxtConfig({runtimeConfig: {public: {env: process.env.NODE_ENV}}})
Then, in the pages you can check the environment to decide to include draft records or not:
<script setup>const QUERY = `query {blog {seo: _seoMetaTags {attributescontenttag}}}`;const config = useRuntimeConfig()const { data, error } = await useGraphqlQuery({query: QUERY,includeDrafts: config.env !== 'production'});</script>