Tyler Dawson

I make apps, games, and whatevers.

Sorting Entries By Date in a Nuxt Content Blog

I'm incrementally building up this blog using the Nuxt Content module.

One issue I caught after three posts was that the entries weren't being sorted properly. As with most blogs, I want my posts sorted by most recent first. A quick search revealed a nuxt-content-git module sets values based on Git activity. That may be exactly what you're looking for. I wanted something even simpler.

Adding Date to Nuxt Content Blog

While there is no date native parameter in the front matter, I added my own:

---
title: ...
description: ...
slug: ...
date: 2023-01-25
---

You could add a full timestamp, but this was sufficient for me. Sure enough, my document's date was there, waiting to be formatted:

<article v-if="data" v-for="post in data" class="mb-4">
  <h2 class="cursor text-xl font-bold text-teal-800 underline">
    <a :href="post.slug">{{ post.title }}</a>
  </h2>
  <p>{{ post.date }}</p>
  <p>{{ post.description }}</p>
</article>

Sorting By Date

Now that we have the date stored, all we have to do is modify the queryContent to sort:

queryContent("blog").sort({ date: -1 }).find()

Going Further?

You could easily build upon this with a createdDate and an updatedDate even without the plugin. Sure, it's one more thing to add to every post, but I enjoy having all the meta data in one place in the front matter. Or add entirely different parameters. How do you use the front matter in your posts?