MW
Home Snippets Astro getCollection — sort by date

Astro getCollection — sort by date

Sort any Astro content collection by date without crashing on missing publishedAt.

TS astro sort content-collections
astro-getcollection-sort.ts
TS 9 lines
Requires: astro:content

When to use this

Anywhere you call getCollection('blog'), getCollection('snippets'), etc. Astro returns entries in filesystem order, not chronological, so anything date-aware needs a sort step. This snippet handles the common edge case of an entry without a publishedAt so the build doesn’t crash mid-deploy.

The code

import { getCollection } from 'astro:content';

export async function getRecentPosts<T extends string>(name: T) {
  const items = await getCollection(name);
  return items.sort((a, b) => {
    const ta = a.data.publishedAt ? new Date(a.data.publishedAt).getTime() : 0;
    const tb = b.data.publishedAt ? new Date(b.data.publishedAt).getTime() : 0;
    return tb - ta;
  });
}

How it works

new Date('') returns Invalid Date, whose .getTime() is NaN. Comparing NaN in a sort puts the entry in random positions and silently corrupts your homepage feed. The ternary forces missing dates to sort to the back (timestamp 0).

Use it like:

const posts = (await getRecentPosts('blog')).slice(0, 3);

The generic <T extends string> keeps Astro’s collection-name typing intact so you still get IntelliSense on .data.*.

Pro tip

Treat this snippet as the starting point — adapt names, types, and edge-case handling to your project. The shape is reusable; the details are yours.

Was this snippet helpful?

Get weekly notes in your inbox

Practical tips, tutorials and resources. No spam.