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.*.
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.