Appearance
System
Light
Dark
Setting applies to this browser only

Querying Content


Fetching All Entries

The getCollection() function is your primary tool for querying content. It returns all entries in a collection:

import { getCollection } from 'astro:content';

const allPosts = await getCollection('blog');

Each entry has the following properties:

  • id — The unique identifier (file path relative to the collection directory)
  • slug — A URL-friendly version of the file name
  • data — The typed frontmatter (validated against your schema)
  • body — The raw Markdown content string
  • collection — The name of the collection
  • render() — A function to render the Markdown to HTML

Filtering Entries

Pass a filter function as the second argument to getCollection() to narrow results:

// Only published posts
const publishedPosts = await getCollection('blog', ({ data }) => {
  return !data.draft;
});

// Posts with a specific tag
const astroPosts = await getCollection('blog', ({ data }) => {
  return data.tags.includes('astro');
});

// Posts from a specific date range
const recentPosts = await getCollection('blog', ({ data }) => {
  const sixMonthsAgo = new Date();
  sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
  return data.pubDate >= sixMonthsAgo;
});

The filter function receives the same type information as your schema, so you get autocompletion for data fields.

Sorting Entries

Since getCollection() returns an array, you can sort using standard JavaScript array methods:

// Sort by publication date (newest first)
const sortedPosts = (await getCollection('blog'))
  .filter(({ data }) => !data.draft)
  .sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());

For docs, you might sort by an order field:

const sortedDocs = (await getCollection('docs'))
  .sort((a, b) => a.data.order - b.data.order);

Rendering Content

To render a collection entry’s Markdown body as HTML, use the render() function in your page components:

---
import { getCollection, render } from 'astro:content';

const allPosts = await getCollection('blog');
---

{allPosts.map(async (post) => {
  const { Content } = await render(post);
  return <Content />;
})}

For individual entry pages, use getEntry() with dynamic routes:

---
import { getCollection, render } from 'astro:content';

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => ({
    params: { slug: post.slug },
    props: { post },
  }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---

<h1>{post.data.title}</h1>
<Content />

Getting a Single Entry

Use getEntry() when you know the specific collection and slug:

import { getEntry } from 'astro:content';

const post = await getEntry('blog', 'getting-started-astro');

This is useful for sidebar navigation, featured posts, or any situation where you need a specific content entry.

Home
Search
Menu
Theme
Top