
Astro collections
Best way to manage your content in Astro
Content collections are the best way to manage content in any Astro project. Using the Content layer API we can define a collection to provide automatic TypeScript type-safety for all of our content.
What are Content Collections?
Let’s say we want to build our personal blog using Astro; using a collection we can turn a bunch of Markdown files (or MDX, Markdoc, YAML, or JSON files) stored locally in our project as the source of our blog content.
NOTE
This API allows us to load local content (aka files in our filesystem), but there are also third-party loaders (our create our own custom loader) to fetch the content from remote sources (think headless CMS).
Defining a Collection
To define a collection, we must create a src/content.config.ts
file in your project, which Astro will use to configure your content collections (we can define many collections).
import { z, defineCollection } from 'astro:content'
// Create the collectionexport const posts = defineCollection({ // type: 'content', // CAN'T USE THIS WITH LOADERS! loader: glob({ pattern: ['!_**/*.md','**/*.md'], base: './posts' }), schema: ({ image }) => z.object({ title: z.string(), author: z.string(), tags: z.array(z.string()), description: z.string(), date: z.date(), }),})
// Export the collectionexport const collections = { posts,}
This file used to go in src/content/config.ts
(the old location, Astro API moves fast), but apparently, now it has to be placed in src/content.config.ts
. The glob
function allows us to do two things:
- Set the folder for our collection, using
base
(relative to project root). - Exclude some folder/files from being parsed, using the
pattern
option (!_**/*.md
won’t match folders starting with un underscore)
NOTE
We are using TypeScript file (*.ts
) to configure our collection, but it’s also possible to use JavaScript (with the .js
extension) to define our collection; or even a Michael Jackson file (.mjs
).