Nuxt 3 Quick start guide

Estimated duration: 10 minutes

This guide shows you how to connect Prepr to a Nuxt 3 project to get data from Prepr CMS. You'll learn how to make a simple blog with Nuxt and Prepr CMS. By the end of this guide, you'll have a working app that looks like the image below.

Blog site end result

If you want to skip ahead, try out the zero installation demo on Stackblitz (opens in a new tab) or clone the repository on GitHub (opens in a new tab) to run the demo locally.


You can also watch the video for step-by-step instructions that are detailed in the guide below.



This video was created using AI avatars and voices to ensure a consistent look and feel. The use of AI matches our culture of using innovative technologies.

Prerequisites

You need to have the following setup before you connect your Nuxt project to Prepr.

Step 1: Create a new Nuxt project

This guide is based on Nuxt 3. The instructions below will guide you on how to create an empty Nuxt project for your blog app.

If you have an existing Nuxt 3 project then you can skip this step.

  1. Open a terminal and execute the following command to create a new Nuxt project called prepr-nuxt:
npx nuxi init prepr-nuxt
  1. When the project is successfully created, go to the prepr-nuxt folder, the root directory of the project, and run the project with the following commands in the terminal:
cd prepr-nuxt
 
npm install
npm run dev
  1. You should now be able to view your app on your localhost, for example, http://localhost:3000/ (opens in a new tab).

  2. Open your Nuxt project with your preferred code editor.

  3. Update the app.vue file with the following code to display your blog:

./app.vue
<template>
  <div>
    <h1>My blog site</h1>
  </div>
</template>

You should now see something like the image below on your localhost.

view component

Step 2: Install the Nuxt Apollo client

The Apollo client is an integration tool that helps to retrieve CMS data with GraphQL. The instructions below show you how to install the Nuxt Apollo client (opens in a new tab) so that you can execute GraphQL queries to request data from the Prepr API.

  1. Stop the server you started in the above step (CTRL-C) and run the following command in the terminal:
npm i -D @nuxtjs/apollo@next
  1. Create a folder called apollo in the root directory of your project. Then, create a file called prepr.ts in this folder. Copy the following code to this file to import the Apollo client:
./apollo/prepr.ts
import { defineApolloClient } from "@nuxtjs/apollo";
 
export default defineApolloClient({
  httpEndpoint: "https://graphql.prepr.io/graphql",
  defaultOptions: {},
  inMemoryCacheOptions: {},
  tokenName: "apollo:prepr.token",
  tokenStorage: "cookie",
  authType: "Bearer",
  authHeader: "Authorization",
  httpLinkOptions: {
    headers: {
      Authorization: `Bearer ${process.env.PREPR_ACCESS_TOKEN}`,
    },
  },
});
  1. Next, open the nuxt.config.ts file and add the apollo module with the following code:
./nuxt.config.ts
import { defineNuxtConfig } from 'nuxt/config'
 
export default defineNuxtConfig({
  modules: ['@nuxtjs/apollo'],
  apollo: {
    clients: {
        prepr: './apollo/prepr.ts',
    },
  },
 
  // If deploying with Vercel, add config below
  build: {
    transpile: ["tslib"],
  },
})
  1. We recommend using environment variables to store sensitive information like access tokens. To add environment variables, create a .env file in the root directory of your project and add the access token like this:
./.env
PREPR_ACCESS_TOKEN=<YOUR-ACCESS-TOKEN>
  1. Replace the placeholder value <YOUR-ACCESS-TOKEN> with an access token from Prepr. Get an access token by logging into your Prepr account:
    a. Go to Settings → Access tokens to view all the access tokens.
    b. Copy the GraphQL Production access token to only retrieve published content items on your site.

access token list

Use the GraphQL Production access token to request published content items for your live app and use the GraphQL Preview token to make a preview of unpublished content items for your content editors.

  1. Execute the following commands to make sure that the Apollo client is installed correctly:
npm install
npm run dev

If your app runs without errors, then the setup above was done correctly. The next step is to fetch content from Prepr using the installed Apollo client.

Step 3: Fetch multiple articles

Now that your Apollo client is installed and connected to Prepr, fetch the blog articles from Prepr.

Add a GraphQL query

  1. Create a queries directory in the root directory of your project and create a file named get-articles.js.

  2. Add the following query to this file to retrieve all articles:

./queries/get-articles.js
export const GetArticles = gql`
 query {
    Articles {
    items {
      _id
      _slug
      title
    }
  }
 }`

You can create and test GraphQL queries using the Apollo explorer (opens in a new tab) from Prepr. Open the API Explorer from the Article content item page in Prepr or the access token page.

If you’re using preloaded demo data in your Prepr CMS environment as mentioned above in the Prerequisites section, you should have a few published articles as shown in the below image. The query will retrieve the ID, Slug, and Title of each article.

demo articles

In the next step, we'll fetch and process the query response.

Fetch data

Now that the query has been added, fetch the articles from Prepr and display them in the app.

  1. Open the app.vue file and replace the content with the following code to display the data retrieved from the query:
./app.vue
<template>
  <div>
    <h1>My blog site</h1>
    <ul>
 
      <!-- Loop through the articles array -->
      <li :data="article" v-for="(article, index) in articles" :key="article._id">
        {{ article.title }}
      </li> 
      
    </ul>
  </div>
 </template>
 
<script setup>
  
  // Import the query
  import { GetArticles } from "@/queries/get-articles";
 
  // Request the data from Prepr
  const { data } = await useAsyncQuery(GetArticles);
 
  // Assign the articles variable to all the articles from Prepr 
  const articles = data.value.Articles.items;
 
  /* Optional: Print query output to the terminal */
  console.log(JSON.stringify(articles, undefined, 2));
 
 </script>

Now when you view the website on your localhost, you'll see something like the image below.

articles on site

Step 4: Fetch individual articles

Now that you have the list of articles, add links to them. When a visitor clicks on a link, your app should open a detailed article page automatically. The instructions below show you how to create the dynamic routing from the main page to the detailed page and how to fetch the article details based on the slug of the article that was clicked.

Create dynamic routing

First add links to the articles.

  1. Update the app.vue file to include a nuxt-link tag on each article title as shown in the code below.
./app.vue
<template>
  <div>
    <h1>My blog site</h1>
    <ul>
      <li :data="article" v-for="(article, index) in articles" :key="article._id">
        <!-- 
          Add a link to each article title and include the article slug in the path 
        -->
        <nuxt-link :to="`/${article._slug}`">
          {{ article.title }}
        </nuxt-link>
      </li>      
    </ul>
  </div>
 </template>
 
 <script setup>
 
  import { GetArticles } from "@/queries/get-articles";
 
  const { data } = await useAsyncQuery(GetArticles);
  const articles = data.value.Articles.items;
 
  console.log(JSON.stringify(articles, undefined, 2));
 
 </script>

Nuxt reads all the .vue files inside a pages directory and automatically creates the router configuration, so setting up the routing is simple.

  1. To set up the automatic routing, create a pages folder.
  2. Move the app.vue file to the pages folder and rename it to index.vue.

Now when you view the app, each article has its own link. When you click on the link, a new page opens with the slug in the URL, but the article details are not yet visible. Continue with the next step to fetch the article details.

Fetch article details

Add another query to fetch a specific article by its slug and make this page visible when clicking on an article.

  1. Create a file called get-article-by-slug.js in the queries folder and add the following query to this file to query a specific article by its slug:
./queries/get-article-by-slug.js
export const GetArticleDetail = gql`
query ($slug: String) {
   Article (slug: $slug) {
     _id
     title
     content {
       __typename
       ... on Text {
         body
         text
       }
       ... on Assets {
         items {
           url
         }
       }
     }
   }
}`

Now that the query is added, fetch the individual article by its slug. Fetch the article title and the article content.

The Article content is stored in a Dynamic content field. Check out the GraphQL docs for more details on how to fetch the data within this field.

  1. Open the pages folder and create a new file [slug].vue with the following code:
./pages/[slug].vue
<template>
    <!-- Display title -->
    <h1 >
        {{ article.title }}
    </h1>
    <!-- Loop through the article content -->
    <div :key="contentType._id" v-for="contentType in article.content">
 
    <!-- Display images if they exist -->
      <div v-if="contentType.__typename === 'Assets'" class="my-10">
        <img
          v-if="contentType.items.length"
          :src="contentType.items[0]?.url"
          width="300" 
          height="250"
        />
      </div>
 
      <!-- Display the text in HTML format -->
      <div
        v-if="contentType.__typename === 'Text'"
        v-html="contentType.body"
      ></div>
    </div>
</template>
   
<script setup>
  import { useRoute } from "vue-router";
  import { GetArticleDetail } from "@/queries/get-article-by-slug";
 
  // Use vue-router to determine the slug in the URL
  const route = useRoute();
  const slug = route.params.slug;
  
  // Request an article by the slug
  const articleQuery = await useAsyncQuery(GetArticleDetail, {
      "slug": slug
  });
 
  // Assign the article variable to the article content from Prepr
  const article = articleQuery.data.value.Article;
 
  </script>

Now, when you view your site, you can click on an article which will direct you to that specific article like in the image below.

Article end result

All done

Congratulations! You have successfully connected a Nuxt project to Prepr for a simple Blog app.

Next steps

To learn more on how to expand your project, check out the following resources:

Was this article helpful?

We’d love to learn from your feedback