Organizing .md files with timestamps in Nuxt

2021-08-09 2 min read

If you are using static site generators, you will be dealing with Markdown files with the .md extension. Confusion arises especially as the number of .md files increases.

For example, let's see the following example:

├── daphne-gunicorn.md
├── just-a-command-runner.md
└── django-serve-txt.md

Wouldn't it be better if it was as below:

├── 2021-07-30--daphne-gunicorn.md
├── 2021-07-31--just-a-command-runner.md
└── 2021-08-07--django-serve-txt.md

The order is now more apparent, and we can easily see at a glance which files belong to which year or month. Now I will explain how we can create this structure in Nuxt.

Let's start by making the following change.

nuxt.config.js
export default {
  hooks: {
    // 2021-12-12--post-slug > post-slug
    'content:file:beforeInsert': (document) => {
      if (document.extension === '.md') {
        const regex = /^(\d{4}-\d{2}-\d{2})--/g
        if (document.slug.match(regex)) {
          document.slug = document.slug.replace(regexpRule, '')
        }
      }
    },
  },
}

Now Nuxt will automatically remove the leading date when creating the slug for these files.

This change necessitates another minor change. Normally, when visiting the path /notes/daphne-gunicorn, we would find the corresponding file inside the notes folder using the slug part (daphne-gunicorn) of that path:

const note = await $content('notes', params.slug)

This is no longer possible as the relation between the slug and the filename is corrupted due to the change we made. We can solve this. You should fetch the content as below:

const [note] = await $content('notes')
  .where({ slug: params.slug })
  .limit(1)
  .fetch()
Date: 2021-08-09
Categories: development