How to Use getCollection in Astro for Content Collections
In Astro, use
getCollection to fetch content from a named collection defined in your project. It returns an array of content entries you can loop over to display data in your components or pages.Syntax
The getCollection function takes the name of a content collection as a string and returns a promise that resolves to an array of entries from that collection.
Use await getCollection('collectionName') inside an async function or top-level await in Astro components.
Each entry contains metadata and content you defined in your collection files.
typescript
import { getCollection } from 'astro:content'; const entries = await getCollection('blog');
Example
This example shows how to fetch all entries from a blog collection and display their titles and dates in an Astro component.
astro
--- import { getCollection } from 'astro:content'; const posts = await getCollection('blog'); --- <ul> {posts.map(post => ( <li key={post.id}> <strong>{post.data.title}</strong> - <em>{post.data.date.toISOString().split('T')[0]}</em> </li> ))} </ul>
Output
<ul><li><strong>My First Post</strong> - <em>2024-05-01</em></li><li><strong>Another Post</strong> - <em>2024-05-10</em></li></ul>
Common Pitfalls
- Forgetting to
awaitthegetCollectioncall causes unresolved promises instead of data. - Using a collection name that is not defined in your
src/content/config.tsor content folder results in errors. - Trying to use
getCollectionoutside of an Astro component or server-side context will fail.
typescript
/* Wrong: Missing await */ const posts = getCollection('blog'); // posts is a Promise, not data /* Right: Using await */ const posts = await getCollection('blog');
Quick Reference
- Import:
import { getCollection } from 'astro:content'; - Usage:
const entries = await getCollection('collectionName'); - Returns: Array of content entries with metadata and body
- Context: Use inside Astro components or server-side scripts
Key Takeaways
Always use await with getCollection to get the actual content data.
getCollection fetches entries from a named content collection defined in your project.
Use getCollection inside Astro components or server-side code only.
Check your collection name matches what you defined in your content config.
Each entry returned includes metadata and content you can render in your UI.