This is an extension to 📝 Generating Slug From Title In Astro

The changes are similar to the previous article but will require an additional library to format the timestamp from frontmatter.

slugDate function #

First install moment

pnpm add moment

Next create a new function in src/lib/slugDate.ts

import { default as moment } from 'moment'
export default function (date: string) {
  const m = moment(date)
  date = `${m.format('YYYY')}/${m.format('MM')}/${m.format('DD')}/`
  return date

Slug Generation #

Call slugDate referencing aswell as createSlug referencing

toISOString is required to change date to a string for types.

// src/pages/blog/[...slug].astro
export async function getStaticPaths() {
  const posts = await getCollection("blog");
  return => ({
-    params: { slug: createSlug( },
+    params: {
+      slug:
+        slugDate( +
+        createSlug(,
+    },
    props: post,
type Props = CollectionEntry<"blog">;

Blog Post Links #

Similar to above call slugDate referencing aswell as createSlug referencing

// src/pages/blog/index.astro
-  <a href={`/blog/${createSlug(}/`}>
+  <a href={`/blog/${slugDate(}
+  ${createSlug(}/`}>

Bonus #

Now all blog posts are using YYYY/MM/DD/title there is no need for /blog/ so it is now possible to move src/pages/blog/[...slug].astro to src/pages/[...slug].astro as all blog posts will have unique slugs.

This cleans up urls a bit & is the same setup I have on my gatsby site.

Source #

The source for my astro blog is available on github.