The Astro content layer is the system behind content collections: each collection in src/content.config.ts has a loader that fetches entries, and an optional schema that validates them. Astro ships two built-in loaders, glob() for folders of Markdown, MDX or data files and file() for a single JSON, YAML or TOML file, and you can write your own loader to pull content from any API.
This guide explains how loaders work in Astro 7, shows each built-in loader with real config, and walks through writing a custom loader with caching and validation.
Key Takeaways
- Collections live in
src/content.config.ts, and every collection needs aloader.glob()loads one entry per file;file()loads many entries from one file.- A loader can be a plain async function that returns an array, or an object with a
load(context)method.- Custom loaders write to
context.storeand validate withcontext.parseData().- Content is loaded at build time and cached in a data store, so pages query it with
getCollection()andgetEntry().
What the content layer does
Before Astro 5, content collections only read files from src/content/. The content layer replaced that with a pluggable model. A collection describes where its data comes from, Astro runs the loader during astro sync, astro dev and astro build, and the results go into a local data store that pages query with the same functions regardless of the source.
That means a blog folder, a JSON file of team members and a headless CMS all look identical from a page’s point of view:
---
// src/pages/index.astro
import { getCollection } from 'astro:content';
const posts = await getCollection('blog');
const team = await getCollection('team');
---
If you are new to collections, start with the Astro content collections guide, then come back here for the loader details.
The config file
All collections are defined in one file at src/content.config.ts:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob, file } from 'astro/loaders';
import { z } from 'astro/zod';
const blog = defineCollection({
loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
draft: z.boolean().default(false),
}),
});
const team = defineCollection({
loader: file('src/data/team.json'),
schema: z.object({
name: z.string(),
role: z.string(),
photo: z.string().optional(),
}),
});
export const collections = { blog, team };
Two imports changed in recent versions. Loaders come from astro/loaders, and Zod now comes from astro/zod. Importing z from astro:content still works in Astro 7 but is deprecated and marked for removal in Astro 8. The older src/content/config.ts location without loaders is legacy; if you see an error about it, the legacy content config fix shows the migration.
The glob() loader
glob() creates one entry per matching file. It takes a pattern and a base directory:
// src/content.config.ts (excerpt)
const docs = defineCollection({
loader: glob({
pattern: ['**/*.md', '!**/_*.md'],
base: './src/content/docs',
}),
});
Patterns can be a string or an array, and a leading ! excludes matches, which is handy for draft or partial files that start with an underscore. Markdown and MDX entries are rendered, so you can pass them to render(). JSON, YAML and TOML files matched by glob() become data-only entries.
Each entry gets an id generated from its path relative to base. src/content/docs/guides/setup.md becomes guides/setup. If a file’s frontmatter has a slug field, that is used as the id instead. To control ids yourself, pass generateId:
// src/content.config.ts (excerpt)
const changelog = defineCollection({
loader: glob({
pattern: '*.md',
base: './src/content/changelog',
generateId: ({ entry }) => entry.replace(/\.md$/, '').replace(/^\d{4}-\d{2}-\d{2}-/, ''),
}),
});
That turns 2026-10-15-new-search.md into the id new-search. Ids must be unique per collection, and a collision produces the duplicate id error covered in the duplicate entry slug fix.
glob() also accepts retainBody (default true; set false to drop the raw body and save memory) and deferRender, which postpones rendering Markdown until a page actually renders the entry. Both help on collections with thousands of files.
The file() loader
file() reads one file and turns each item into an entry. It understands JSON, YAML and TOML by extension:
// src/data/team.json
[
{ "id": "ana", "name": "Ana Ruiz", "role": "Design lead" },
{ "id": "sam", "name": "Sam Okafor", "role": "Developer" }
]
The file must be either an array of objects with unique id fields, or an object whose keys become the ids:
# src/data/services.yaml
branding:
title: Brand identity
price: 4000
websites:
title: Website design
price: 8000
For any other format, pass a parser. Here is a CSV file using a tiny hand-written parser:
// src/content.config.ts (excerpt)
const locations = defineCollection({
loader: file('src/data/locations.csv', {
parser: (text) => {
const [header, ...rows] = text.trim().split('\n');
const keys = header.split(',');
return rows.map((row) => Object.fromEntries(row.split(',').map((v, i) => [keys[i], v])));
},
}),
schema: z.object({ id: z.string(), city: z.string(), country: z.string() }),
});
For real CSV with quoted fields, use a proper parsing library inside parser. The CSV data tip has a complete example.
Inline loaders: a function that returns an array
The quickest custom loader is a function. Astro calls it at build time and stores whatever it returns:
// src/content.config.ts (excerpt)
const releases = defineCollection({
loader: async () => {
const res = await fetch('https://api.github.com/repos/withastro/astro/releases?per_page=20');
const data = await res.json();
return data.map((release: { tag_name: string; name: string; published_at: string; html_url: string }) => ({
id: release.tag_name,
name: release.name,
publishedAt: release.published_at,
url: release.html_url,
}));
},
schema: z.object({
name: z.string(),
publishedAt: z.coerce.date(),
url: z.url(),
}),
});
Each returned object needs an id. The schema still runs, so a bad API response fails the build with a clear message rather than breaking a page at runtime. Inline loaders are ideal for small, read-only sources where you don’t need caching between builds.
Writing an object loader with context
For anything larger, write a loader object. It has a name and a load(context) method, and it talks to the store directly:
// src/loaders/products-loader.ts
import type { Loader } from 'astro/loaders';
export function productsLoader(options: { url: string }): Loader {
return {
name: 'products-loader',
load: async ({ store, parseData, generateDigest, meta, logger }) => {
const lastModified = meta.get('last-modified');
const res = await fetch(options.url, {
headers: lastModified ? { 'If-Modified-Since': lastModified } : {},
});
if (res.status === 304) {
logger.info('Products unchanged, using cached entries');
return;
}
const products: Array<Record<string, unknown> & { sku: string }> = await res.json();
store.clear();
for (const product of products) {
const data = await parseData({ id: product.sku, data: product });
store.set({ id: product.sku, data, digest: generateDigest(data) });
}
const header = res.headers.get('last-modified');
if (header) meta.set('last-modified', header);
logger.info(`Loaded ${products.length} products`);
},
};
}
// src/content.config.ts (excerpt)
import { productsLoader } from './loaders/products-loader';
const products = defineCollection({
loader: productsLoader({ url: 'https://shop.example.com/api/products.json' }),
schema: z.object({ sku: z.string(), title: z.string(), price: z.number() }),
});
What each part of the context does:
| Context field | Purpose |
|---|---|
store |
The collection’s entries: set, get, delete, clear, keys, entries |
parseData() |
Validates data against the collection schema and returns the parsed result |
generateDigest() |
Hashes data so Astro can skip unchanged entries |
meta |
A small key-value store for sync tokens or timestamps, persisted between builds |
renderMarkdown() |
Renders a Markdown string to HTML so entries work with render() |
logger |
Prefixed logging in the terminal |
watcher |
In dev, a file watcher you can use to reload on changes |
If your source returns Markdown, call renderMarkdown(body) and pass the result as rendered in store.set(). Pages can then use render(entry) exactly as they would for a local file. The loader API reference lists every field.
Querying loaded content in pages
Once loaded, every collection is queried the same way:
---
// src/pages/blog/[id].astro
import { getCollection, render } from 'astro:content';
export async function getStaticPaths() {
const posts = await getCollection('blog', ({ data }) => !data.draft);
return posts.map((post) => ({ params: { id: post.id }, props: { post } }));
}
const { post } = Astro.props;
const { Content, headings } = await render(post);
---
<article>
<h1>{post.data.title}</h1>
<Content />
</article>
getCollection() takes an optional filter. getEntry('team', 'ana') fetches one entry by id. Entries have id, data, and for rendered content, body and rendered. The old slug property and entry.render() method belong to the legacy API. See getStaticPaths in Astro, explained for the routing side.
Everything above runs at build time. If content must be fresh on every request, Astro also has live collections defined with defineLiveCollection() in src/live.config.ts, which fetch at request time on a server-rendered site. For a static theme, build-time loaders are the right default, and they are what most Astro blog themes use. The content docs show the collection setup used in Komal themes.
FAQ
What is the Astro content layer?
The content layer is the loader-based system behind Astro content collections, introduced in Astro 5. Each collection declares a loader that fetches entries from files, APIs or a CMS, and Astro stores the results so pages can query them with getCollection() and getEntry().
What is the difference between glob() and file() in Astro?
glob() matches many files and creates one entry per file, which suits Markdown and MDX posts. file() reads a single JSON, YAML or TOML file and creates one entry per item in it, which suits lists like team members, FAQs or locations.
Do I need a schema with a custom loader?
No, but you should add one. Without a schema, data is stored as-is and typed loosely. With a schema, parseData() validates every entry, the build fails on bad data, and getCollection() returns fully typed entries.
Where does Astro store loaded content?
In a data-store.json file that Astro caches between builds. That is what makes rebuilds faster: loaders can compare digests or use meta to skip work when nothing has changed.
Can a loader fetch content from a headless CMS?
Yes. A loader is just code that runs at build time, so it can call any API. Many CMS vendors publish loaders as npm packages, and you can write your own in a few dozen lines using store.set() and parseData().