"Why do I need a
slugin my frontmatter if my file is already namedmy-cool-post.mdx?"
I asked myself this at 2am, right after my build broke for the third time because I renamed a file.
Let's talk about why slugs matter, and how to make your blog system both flexible and future-proof.
The "Just Use the Filename" Approach
It's tempting.
You name your file my-cool-post.mdx, and your blog loader just uses that as the slug.
Simple, right?
- No extra fields.
- No confusion.
- No chance of typos between filename and slug.
But then...
- You want to rename your file for organization (
2024-06-05 my-cool-post.mdx). - Or you want to change the URL slug for SEO, but keep the file name for your own sanity.
- Or you want to add categories, or dates, or anything else to the filename.
Suddenly, your URLs break.
Old links 404.
Google gets sad.
You get sad.
Enter: The slug Field
By adding a slug field to your frontmatter, you decouple the URL from the filename.
---
title: "My Cool Post"
slug: my-cool-post
---Now you can:
- Rename your file whenever you want.
- Change the slug for SEO or aesthetics.
- Keep old URLs working, even if you reorganize your content.
The Best of Both Worlds: Slugify Fallback
But what if you forget to add a slug?
Or you're migrating old posts?
That's where the slugify fallback comes in:
- If
slugis present in frontmatter, use it (slugified for safety). - If not, slugify the filename.
This way, you get:
- Flexibility for power users.
- Simplicity for everyone else.
How My Loader Works (Nerd Flow)
Here's the nerdy bit:
+---------------------+
| Read .mdx files |
+---------------------+
|
v
+----------------------------+
| Parse frontmatter/meta |
+----------------------------+
|
v
+--------------------+
| Slug specified? |
+--------+-----------+
| Yes | No
v v
+-------------------+ +----------------------+
| Use frontmatter | | Slugify filename |
| slug (safe/clean) | | (e.g., kebab-case) |
+-------------------+ +----------------------+
\ /
\ /
v v
+------------------------+
| Map slug to route |
+------------------------+
|
v
+------------------------+
| Serve at /blog/[slug] |
+------------------------+Result:
You can have files named 2024-06-05 My Cool Post.mdx with a slug of my-cool-post, and your URLs stay clean and unbreakable.
Why This Matters
- No more broken links when you reorganize.
- SEO-friendly URLs without weird filenames.
- Happier you (and happier Google).
TL;DR
- Use a
slugin your frontmatter for flexibility. - Fallback to slugified filename for simplicity.
- Never break your URLs again.
- In case of errors make sure your loader is updated to support arbitrary filenames.
"Build systems that work for you, not against you.
Slugify, decouple, and geek out."