Defining Collections

One Config File Declares Every Collection

Defining Collections

`src/content.config.ts` is the single place you declare your collections — their loaders and schemas.

4 min read Level 2/5 #astro#content-config#defineCollection
What you'll learn
  • Author `src/content.config.ts`
  • Use `defineCollection` and `glob`
  • Export collections for Astro to pick up

Every collection is declared in src/content.config.ts. The file exports an object that maps collection names to their definitions.

The Shape

// src/content.config.ts
import { defineCollection, z } from "astro:content";
import { glob } from "astro/loaders";

const blog = defineCollection({
  loader: glob({ pattern: "**/*.md", base: "./src/blog" }),
  schema: z.object({
    title: z.string(),
    pubDate: z.coerce.date(),
    tags: z.array(z.string()).default([]),
    draft: z.boolean().default(false),
  }),
});

export const collections = { blog };

Three pieces:

  1. loader — where the entries come from
  2. schema — what fields each entry has (Zod)
  3. Export under the key you’ll use to query

After Editing The Config

Run npm run astro sync (or restart the dev server). This generates types in .astro/. Your editor now knows the shape of getCollection("blog")[number].data.

Multiple Collections

import { defineCollection, z } from "astro:content";
import { glob, file } from "astro/loaders";

const blog = defineCollection({
  loader: glob({ pattern: "**/*.md", base: "./src/blog" }),
  schema: z.object({ title: z.string() }),
});

const authors = defineCollection({
  loader: file("./src/data/authors.json"),
  schema: z.object({
    id: z.string(),
    name: z.string(),
    twitter: z.string().optional(),
  }),
});

export const collections = { blog, authors };

The key (blog, authors) is the name you pass to getCollection(...).

Where Collection Content Lives

Up to you. Common patterns:

  • src/<collection>/src/blog/, src/docs/ (works with base: './src/blog')
  • src/content/<collection>/ — older convention, still common
  • Anywhere else — collections accept any base

Up Next

The most common loader — globbing Markdown/MDX files.

The Glob Loader →