Astro JS - Content Collections



What is Content Collection?

In astro framework, content collections are a way to manage and organize markdown (.md) and markdown with frontmatter (.mdx) content of your project. It is used to define collections, enable schemas, and query content efficiently. Collections help to organize and query your documents, enable intellisense and type checking in your editor, and provide automatic TypeScript type-safety for all of your content.

Key Features of Content Collections

Content collections in Astro provide the following key features:

  • Structured Content Management − Content collections organize markdown files into collections with predefined schemas.
  • Type Safety with Zod − It ensures structure of contents by using Zod schemas for validation.
  • Automatic Type Generation − It ensures type safety when querying content.
  • Flexible Querying − Retrieve and filter content programmatically just like SQL.

Create Content Collections in Astro

Follow the steps below to create content collections in Astro:

Step 1: Define a Collection

First, define a collection inside 'src/contents' directory. Each collection consists of markdown or MDX files. For example, create a 'blog' collection with the following structure:

src/
│── content/
│   ├── blog/   (collection)
│   │   ├── post-1.md
│   │   ├── post-2.md
│   ├── docs/   (collection)
│   │   ├── guide.md
│   │   ├── tutorial.md

Step 2: Define a Schema

A scheme is a way to define the structure of your content. You can define a schema using Zod, a TypeScript-first schema declaration and validation library. Create a schema for your collection using Zod in src/content/config.ts. The code below define a schema , which ensures that each markdown file in the blog collection must contain a title, date, tags, and optionally draft.

// File: src/content/config.ts

import { defineCollection, z } from "astro:content";

const blogCollection = defineCollection({
  schema: z.object({
    title: z.string(),
    date: z.string(),
    tags: z.array(z.string()),
    draft: z.boolean().optional(),
  }),
});

export const collections = {
  blog: blogCollection,
};

Step 3: Query Content

Astro provides helper functions to query a collection and return one (or more) content entries.

  • getCollection() fetches an entire collection and returns an array of entries.
  • getEntry() fetches a single entry from a collection.

These return entries with a unique id, a data object with all defined properties, and will also return a body containing the raw, uncompiled body of a Markdown, or MDX document.

import { getCollection, getEntry } from 'astro:content';

// Get all entries from a collection.
// Requires the name of the collection as an argument.
const allBlogPosts = await getCollection('blog');

// Get a single entry from a collection.
// Requires the name of the collection and `id`
const poodleData = await getEntry('dogs', 'poodle');

When to Use Content Collection?

Content collections are useful in the following scenarios −

  • You have multiple files or data to organize that share the same overall structure (e.g. blog posts written in Markdown which all have the same frontmatter properties).
  • You have existing content stored remotely, such as in a CMS or database, that you want to import into your Astro project.
  • You need to fetch (tens of) thousands of related pieces of data, and need a querying and caching method that handles at scale.
  • Defining a common data shape to validate that an individual entry is “correct” or “complete”, avoiding errors in production.
Advertisements