How to build a CMS-powered blog with Nuxt

How to build a CMS-powered blog with Nuxt

So you just built a new website and need a blog on your new site. How do you do this without spinning up a server? We will look at how to add a blog to our new site powered by just APIs that we can call. Check out what the final project looks like here.

There are a couple of ways we can add a blog to a site. One way is to use a Headless CMS, which will power the blog. In this tutorial, we’ll be looking at what a Headless CMS is, the options available for us to use, and the front-end framework that will be best for our blog.

What is a Headless CMS

Many of us have heard of or come across the term “Headless CMS”. For those who aren’t familiar with the term, it simply refers to a CMS (Content Management System) where the front-end and back-end are decoupled, unlike in a traditional CMS. Unlike a traditional CMS where the front-end can’t be separated from the back-end like with WordPress or Drupal, a headless CMS provides only the back-end functionality and allows you to run your front-end and deploy it wherever and connect to the CMS using APIs. A Headless CMS offers developers much more benefits than a traditional CMS in many ways. One significant advantage is that you can use APIs to connect your front-end to your CMS, which allows for faster development and freedom to use any front-end framework of choice, which is good for DX and UX.

Now that we have an idea of what a Headless CMS is, we’ll look into how we can build a blog powered by a popular, easy-to-setup Headless CMS — ButterCMS.


To follow along, we need to have a few things in place:

What we’ll build

We’ll be building a blog with Nuxt for our front-end and ButterCMS as our back-end. Nuxt (or Nuxt.js) is a front-end framework for Vue (or Vue.js) that provides server-side rendering capabilities and features that will also enhance SEO and page load time for our blog.

Set up Nuxt

Before we jump into setting up Butter, let’s create the front-end we will connect Butter to. We’ll be using Nuxt 3, which is still in beta at the time of writing but offers a lot of new features and allows us to use Vue 3’s composition API. To create a new Nuxt 3 project in your terminal, run:

1npx nuxi init butter-blog

This creates a new butter-blog/ directory, which you can navigate to. Install the dependencies and run the app:

1cd butter-blog

2 yarn install #or npm install

3 yarn dev #or npm run dev

Let’s also install WindiCSS, a Tailwind alternative that works well with Nuxt.

1yarn add nuxt-windicss -D

Once the installation is complete, within your nuxt.config.js add the following:

1import { defineNuxtConfig } from "nuxt3";


3export default defineNuxtConfig({

4 buildModules: ["nuxt-windicss"],


Next, let’s add a header and a home page to our Nuxt app. Go to the ./app.vue file and enter the following lines of code:


2 <div>

3 <header class="sticky top-0 p-4 bg-white">

4 <div

5 class="wrapper flex items-center justify-between w-full max-w-5xl m-auto"

6 >

7 <figure>

8 <NuxtLink to="/">

9 <h1>Butter Blog</h1>

10 </NuxtLink>

11 </figure>

12 <nav>

13 <ul>

14 <li>

15 <NuxtLink to="/blog">Blog</NuxtLink>

16 </li>

17 </ul>

18 </nav>

19 </div>

20 </header>

21 <!-- render pages based on route -->

22 <NuxtPage />

23 </div>


Create a new file, pages/index.vue: the home page of the Nuxt app.

1<!-- pages/index.vue -->


3 <main>

4 <header

5 class="flex flex-col gap-4 items-center justify-center w-full h-screen bg-gray-900 text-gray-100"

6 >

7 <h1 class="font-black text-5xl">Hello!</h1>

8 <p class="text-xl">

9 Go to the

10 <nuxt-link class="underline" to="/blog"

11 >blog</nuxt-link

12 >

13 </p>

14 </header>

15 </main>


We should have something like this:


Great! We can proceed with setting up Butter.

Set up Butter

To get started, sign up and log in to your Butter account to get your Butter API token. You can follow the Butter Quickstart setup page for Nuxt.

Install the Butter SDK

1yarn add buttercms

2 #or npm install buttercms --save

Add API token to Nuxt Runtime configurations
You can copy your API token from the settings page. The API token will be used to initialize our Butter SDK. We can expose config and environment variables to the rest of our app by defining the runtime configuration in our nuxt.config.js file using the publicRuntimeConfig options; more on that in the Nuxt docs.


2import { defineNuxtConfig } from "nuxt3";

3export default defineNuxtConfig({

4 buildModules: ["nuxt-windicss"],

5 publicRuntimeConfig: {


7 },


Next, create a .env file to add the token.



Great! Now we can access our API token in our Nuxt app.

Create a helper for the Butter SDK
To have global access to the Butter SDK in our Nuxt app, we’ll create a plugin and configure it as a helper.. In the plugins/ directory, create a new butter.js file which will automatically be registered as a plugin:



3import { defineNuxtPlugin } from "#app";

4import Butter from "buttercms";


6export default defineNuxtPlugin(() => {

7 const config = useRuntimeConfig();


9 return {

10 provide: {


12 butter: Butter(config.API_TOKEN),

13 },

14 };


In the code above, we import the Butter SDK and get the API token from our private runtime config using useRuntimeConfig().

Fetch content from Butter
Now, it’ll be a good idea to try this out. Butter has an example blog post to get started with, and we’ll be using that to try things out. On your Butter dashboard, navigate to the blog posts page.


Click on the post and open the API Explorer, which allows us to see which endpoint to access for the post and an example response.


Here’s what it looks like with the API explorer.


We can use the Javascript SDK code for fetching this post in our Nuxt app. Let’s set up a quick example to see how this works. Create a new dynamic page pages/blog/[slug].vue




4 <header>

5 <h1>{{ post.title }}</h1>

6 <p>{{ post.summary }}</p>

7 </header>



10<script setup lang="ts">


12const { $butter } = useNuxtApp();

13const { data: post } = await useAsyncData(

14 "posts",

15 async () => {

16 try {

17 let data = await $

18 .retrieve("example-post")

19 .then((res) =>

20 .catch((err) => console.log(err.response));

21 return data;

22 } catch (error) {

23 console.log(error);

24 return [];

25 }

26 }



In the code above, we’re using useAsyncData, which Nuxt provides to fetch or get asynchronous data into our app; more on data fetching in Nuxt in the docs.. Within the useAsyncData block, we’re using the global $butter helper we created earlier to retrieve the example post as shown in the API Explorer. Now, if we navigate to http://localhost:3000/blog/<any-slug>, we’ll see this:


Great! Now that we’ve set up Butter SDK in our Nuxt app, let’s go back to the Butter dashboard to start creating, organizing, and publishing content.

Create a new blog post

It’s pretty easy to create a new blog post using ButterCMS. It provides you with a preconfigured blog post template with all the fields you need to get an SEO-optimized blog up and running quickly. Navigate to Blog Posts > New to create a new blog post. Let’s create our first blog post.

Enter Title and WYSIWYG fields
Enter content into the Title and WYSIWYG(What You See Is What You Get) fields.


Butter’s WYSIWYG editor offers rich features, so feel free to play around and explore.
Next, Butter also offers the ability to enter metadata and SEO optimization fields. We’ll look at this now:

Enter Metadata fields
Metadata fields allow you to enter helpful information about the blog post. Let’s look at some of the fields:

  • Author: With Butter, we can add Authors and their corresponding bio information ****by navigating to the** [Users]([]( page. You can select the Author for our Blog Post from the Author dropdown. It’s set to our user account by default.

  • Publish Date: This is the date the post is published, and we can change it from the default date.

  • Categories & Tags: These are comma-separated values that can be used to organize and filter blog posts

  • Summary: This can be a short description for the blog post.

  • Featured Image: We can also add a featured image to the blog post using Butter’s Media Library.

  • To add a featured image, click on the featured media box that opens up the Media library:

  • Click on the Upload Media button at the top-right corner of the modal to upload an image:

  • Now, we can upload an image from our file manager or drag and drop a file onto the box.

  • Once we’ve uploaded the image, we can insert it by clicking on the Insert Media button at the top.

  • Featured Image Alt Text: Here’s a field we can use to enter the alt text for the featured image.

Here’s what our metadata section looks like now:


Enter SEO fields:
With Butter, we can also optimize our SEO for each blog post by providing SEO fields such as title and description. Butter also has a handy search engine preview which helps keep the text within the character range.


View the post in the API explorer
As we’ve seen earlier, the API explorer allows us to see the Butter SDK in action and the expected response data. This way, we can see the data we’re expecting and know how to work with it. Click on the Save draft button to save the post.


Click on the three dots (…) button and select API Explorer in the dropdown.


Now that we’ve seen what the data looks like, we can close the API explorer and publish the post by clicking on the Publish button.

Update blog post URL slug
We might need to update the default auto-generated slug value for our post for some reason. To do that, open the post from the Blog Posts page and select the blog post. There’s a new URL Slug field in the SEO section where we can update the slug and click on the Update button to save the changes.


Next, we’ll create a few more posts and head over to Nuxt to display our posts on the front end.

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.


Happy debugging, for modern frontend teams – Start monitoring your web app for free.

Display posts in the Nuxt front end

First, we’ll be displaying all the blog posts from Butter. Let’s create a new page pages/index.vue. In the <script>, we’ll import our $butter helper function, pass in pagination options and fetch the first ten pages. Also, since we have categories and tags for our posts, we’ll be fetching all the categories to create a <select> input to filter all the posts by categories. We can also do the same for tags, but we’ll focus on categories for now.

1<!-- pages/index.vue -->


3<script setup>

4const { $butter } = useNuxtApp();

5const posts = ref([]);

6const categories = ref([]);


8posts.value = await $

9 .list({

10 page: 1,

11 page_size: 10,

12 })

13 .then((res) =>

14 .catch((err) => {

15 console.log("ERR ==>", err.response);

16 return [];

17 });

18categories.value = await $butter.category

19 .list()

20 .then((res) => {

21 return;

22 })

23 .catch((err) => {

24 console.log("ERR ==>", err.response);

25 return [];

26 });


In the above code, we’re setting up the posts and categories variables as reactive variables using ref(). Then we set the values by calling $ and $butter.category.list() and assigning the fetched data to posts.value and categories.value respectively. Next, in the template, we’ll create a simple UI to list the posts. We’ll use a v-for= “” “post in posts “” to loop through all the posts and render a <article-card> list item with the post data.

Create article-card component
Create a new component/articleCard.vue component

1<!-- component/articleCard.vue -->


3 <li class="post">

4 <nuxt-link

5 :to="`/blog/${post.slug}`"

6 class="flex flex-col md:flex-row gap-4 w-full bg-white p-4"

7 >

8 <div class="img-cont w-full md:w-40 h-32">

9 <img

10 class="object-cover w-full h-full"

11 :src="post.featured_image"

12 :alt="post.featured_image_alt"

13 />

14 </div>

15 <div

16 class="wrapper flex flex-col justify-between gap-4"

17 >

18 <header>

19 <h1 class="font-bold text-2xl">

20 {{ post.title }}

21 </h1>

22 <p>{{ post.summary }}</p>

23 </header>

24 <ul class="categories flex gap-2">

25 <li

26 v-for="category in post.categories"

27 class="category bg-gray-100 text-gray-800 p-1 px-2"

28 >

29 {{ }}

30 </li>

31 </ul>

32 <footer>

33 <hr class="my-4" />

34 <ul class="flex gap-4 text-gray-600">

35 <li class="author">

36 {{

37 `${} ${}`

38 }}

39 </li>

40 <li class="published">

41 {{ new Date(post.published).toDateString() }}

42 </li>

43 </ul>

44 </footer>

45 </div>

46 </nuxt-link>

47 </li>


49<script setup>



Cool, so here you can see that we’re passing props using the defineProps() macro and rendering the data in the template. Let’s see this in action.

1<!-- pages/index.vue -->



4 <main class="min-h-screen">

5 <header

6 class="page-header flex items-center justify-center h-56 bg-gray-900 text-gray-50 text-center"

7 >

8 <div class="wrapper max-w-5xl m-auto">

9 <h1 class="font-black text-5xl">Posts</h1>

10 <p>View all posts</p>

11 </div>

12 </header>

13 <section class="p-4">

14 <div class="wrapper max-w-5xl m-auto">

15 <form action="" class="filter-form relative p-4">

16 <div class="wrapper">

17 <div class="form-control">

18 <select

19 name="category"

20 id="category"

21 class="bg-gray-50 p-4 shadow"

22 >

23 <option value="">All Categories</option>

24 <option

25 v-for="category in categories"

26 :key="category.slug"

27 :value="category.slug"

28 >

29 {{ }}

30 </option>

31 </select>

32 </div>

33 </div>

34 </form>

35 <ul class="posts flex flex-col gap-4">

36 <article-card

37 v-for="post in posts"

38 :key=""

39 :post="post"

40 />

41 </ul>

42 </div>

43 </section>

44 </main>


Here’s what it should look like:


Next, we’ll work on filter functionality to filter the posts by category.

Filtering posts by categories

There are two ways we can go about filtering our blog posts. We can filter it on the client-side when we’ve fetched all the articles on the blog page using a computed property, or we can create dynamic pages and fetch the categories from Butter with the posts data included.

1. Use a computed property
In pages/index.vue, we’ll use a computed method to filter the posts and return them to a reactive filterdPosts variable.

1<!-- pages/index.vue -->



4// ...


6const activeCategory = ref("");

7const filteredPosts = computed(() => {

8 if (

9 activeCategory.value &&

10 activeCategory.value !== "all"

11 ) {

12 let filteredPosts = posts.value.filter((post) => {

13 return post.categories.some(

14 (cat) => cat.slug === activeCategory.value

15 );

16 });

17 console.log(filteredPosts);

18 return filteredPosts;

19 } else {

20 return posts.value;

21 }



In the code above, we have a reactive activeCategory variable which will be used to set the category to filter posts within the filteredPosts function. In the filteredPosts function, we assign it to a computed method which checks if activeCategory has a value and is not equal to “all”. Then returns the posts that contain that category. With the else block, if activeCategory is ” “all ” or some other value, it’ll return the original posts data. We can implement this in the <template> by modifying the <select> element.

1<!-- pages/index.vue -->


3 ...

4 <select

5 name="category"

6 id="category"

7 class="bg-gray-50 p-4 shadow"

8 >

9 <option

10 value="all"

11 @click="() => (activeCategory = `all`)"

12 >

13 All Categories

14 </option>

15 <option

16 v-for="category in categories"

17 :key="category.slug"

18 :value="category.slug"

19 @click="() => (activeCategory = category.slug)"

20 >

21 {{ }}

22 </option>

23 </select>

24 ...


This sets the activeCategory value to the category.slug of the selected <option>. We can render posts using the computed filteredPosts variable instead.

1<!-- pages/index.vue -->



4 ...

5 <article-card

6 v-for="post in filteredPosts"

7 :key=""

8 :post="post"

9 />

10 ...


2. Use dynamic pages and the Butter **include** query parameter
Since we can fetch all categories using $butter.category.list(), we can go a step further and create dynamic pages for each category. If we want to do the same for other metadata like Authors and Tags, we can easily do so. First, we will create a new category page, pages/blog/category/index.vue, listing all categories.

1<!-- pages/blog/category/index.vue -->



4 <main class="min-h-screen">

5 <header

6 class="page-header flex items-center justify-center h-56 bg-gray-900 text-gray-50 text-center"

7 >

8 <div class="wrapper max-w-5xl m-auto">

9 <h1 class="font-black text-5xl">Categories</h1>

10 <p>View all categories</p>

11 </div>

12 </header>

13 <section class="p-4 py-12">

14 <div class="wrapper max-w-5xl m-auto">

15 <ul

16 class="posts flex flex-row justify-center gap-8"

17 >

18 <li

19 v-for="category in categories"

20 :key="category.slug"

21 class="text-2xl p-4 bg-gray-100 text-gray-800 hover:bg-gray-800 hover:text-gray-100"

22 >

23 <NuxtLink

24 :to="`/blog/category/${category.slug}`"

25 >{{ }}</NuxtLink

26 >

27 </li>

28 </ul>

29 </div>

30 </section>

31 </main>


33<script setup>

34const { $butter } = useNuxtApp();

35const categories = ref([]);

36categories.value = await $butter.category

37 .list()

38 .then((res) => {

39 return;

40 })

41 .catch((err) => {

42 console.log("ERR ==>", err.response);

43 return [];

44 });


We should have something like this:


Great! We can create a dynamic page that will render posts from each category based on the slug. Create a new file pages/blog/category/[slug].vue

1<!-- pages/blog/category/[slug].vue -->



4 <main class="min-h-screen">

5 <header

6 class="page-header flex items-center justify-center h-56 bg-gray-900 text-gray-50 text-center"

7 >

8 <div class="wrapper max-w-5xl m-auto">

9 <h1 class="font-black text-5xl">

10 {{ }}

11 </h1>

12 <p>View all posts</p>

13 </div>

14 </header>

15 <section class="p-4">

16 <div class="wrapper max-w-5xl m-auto">

17 <ul class="posts flex flex-col gap-4">

18 <article-card

19 v-for="post in postsByCategories.recent_posts"

20 :key=""

21 :post="post"

22 />

23 </ul>

24 </div>

25 </section>

26 </main>


28<script setup>

29import ArticleCard from "~~/components/articleCard.vue";

30const route = useRoute();

31const { $butter } = useNuxtApp();

32const postsByCategories = ref([]);

33const slug = route.params.slug;

34postsByCategories.value = await $butter.category

35 .retrieve(slug, {

36 include: "recent_posts",

37 })

38 .then((res) => {

39 return;

40 })

41 .catch((err) => {

42 console.log("ERR ==>", err.response);

43 return [];

44 });


In the code above, we’re retrieving the posts using the $butter.category.retrieve() method. We must add the include: “recent_posts” parameter to return posts in that category. If we navigate to say http://localhost:3000/blog/category/article, we should have something like this:


Beautiful! A little extra thing we can do is to change the current category select to a dropdown button in the blog home page for faster navigation. Let’s create a new component components/categoriesDropDown.vue


2 <div class="categories z-10">

3 <div class="relative group w-42">

4 <div

5 class="flex items-center cursor-pointer border group-hover:border-grey-light py-1 px-2"

6 >

7 <p>All categories</p>

8 <svg

9 class="fill-current h-4 w-4"

10 xmlns=""

11 viewBox="0 0 20 20"

12 >

13 <path

14 d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"

15 />

16 </svg>

17 </div>

18 <div

19 class="items-center absolute border border-t-0 p-1 bg-white p-2 invisible group-hover:visible w-full"

20 >

21 <nuxt-link

22 v-for="category in categories"

23 :key="category.slug"

24 :to="`/blog/category/${category.slug}`"

25 class="block hover:bg-gray-100 p-1 cursor-pointer"

26 >

27 {{ }}

28 </nuxt-link>

29 </div>

30 </div>

31 </div>


33<script setup>



This component takes in categories as props and renders a list of <NuxtLink>’s to the corresponding pages. In pages/blog/index.vue we can replace the current <select>

1<!-- pages/blog/index.vue -->


3 // ...


5 <section class="p-4">

6 <div class="wrapper max-w-5xl m-auto">

7 <!-- replace select form with categories dropdown -->

8 <categories-drop-down :categories="categories" />

9 <ul class="posts flex flex-col gap-4">

10 // ...

11 </ul>


13 // ...

14 </div>

15 </section>




19import CategoriesDropDown from "~~/components/categoriesDropDown.vue";

20// ...


We should have something like this now:

Alright, currently our site sucks at SEO. That’s because we’ve not yet implemented some of the awesome SEO features that Nuxt provides. Let’s fix that.

We can use Nuxt Meta Tags to customize meta tags for our blog. There are multiple ways we can use Meta tags in Nuxt. You can learn more about them in the Nuxt docs. We’ll be using the Meta Components in this tutorial since it is very quick and easy. et’s add meta tags to each of our pages so far.
In app.vue
We’ll add it to the top of the page, within the <template />.

1<!-- app.vue -->



4 <div>

5 <Head>

6 <Title> My CMS powered blog </Title>

7 <Meta

8 name="description"

9 content="Welcome to my CMS powered blog! Enjoy!"

10 />

11 </Head>

12 // ...

13 </div>


See it in action:


Let’s add some dynamic meta tags to our blog post page.
In **pages/blog/[slug].vue**
Since this is a dynamic page, we will pass the data in from post data fetched from Butter. Here are a few tags important tags we can add:

1<!-- pages/blog/[slug].vue -->



4 <main>

5 <Head>

6 <Title> {{ post.title }} </Title>

7 <Meta name="description" :content="post.summary" />

8 <Meta property="og:title" :content="post.title" />

9 <Meta name="twitter:title" :content="post.title" />

10 <Meta

11 property="og:description"

12 :content="post.summary"

13 />

14 <Meta

15 name="twitter:description"

16 :content="post.summary"

17 />

18 <Meta

19 property="og:image"

20 :content="post.featured_image"

21 />

22 <Meta

23 property="twitter:image"

24 :content="post.featured_image"

25 />

26 </Head>

27 ...

28 </main>


Here’s what it should look like:


Awesome! Now we can add meta tags to the rest of our pages to really boost our SEO. You can check out the GitHub code here.


So we’ve managed to build a CMS-powered blog with ButterCMS and NuxtJS. ButterCMS has tons of other features, and we just covered the blog post feature. Butter also allows you to build pages and collections as content types. You can always access them on your dashboard and see how to use them using the API Explorer. Nuxt also allows us to build our blog with powerful and useful features like dynamic routing, meta tags, and more. Feel free to explore and try out more of the features Butter offers and how you can make them work hand-in-hand with NuxtJS.

Source link

Leave a reply

Please enter your comment!
Please enter your name here