Data and Content Management
Content Collections add types/validation to Markdown/MDX; fetch data at build time when possible to reduce runtime load.
Content Collections
- Define collections:
defineCollectioninsrc/content/config.tswith schema/types. - Type-safety: Zod/schema validates frontmatter and generates types.
- Query:
getCollection('posts')to read/filter/sort. - Example:
// src/content/config.ts import { defineCollection, z } from 'astro:content'; const posts = defineCollection({ schema: z.object({ title: z.string(), date: z.date(), tags: z.array(z.string()).optional(), }), }); export const collections = { posts };
Data fetching
- Static data:
const data = await fetch(...)at top of the page—runs at build and writes into static HTML. - API integration: use
fetch/await; if sources are unstable, move toonRequest(SSR) or incremental generation. - Dynamic import:
const md = await import('../../data/foo.json');bundles at build time. - Prefetch: for list+detail, prefetch lists at build and generate static detail pages.
Markdown/MDX enhancements
- Frontmatter: store metadata (title/description/tags).
- MDX: embed components for reusable UI (callouts, charts).
- Highlighting: built-in code highlight or configure Shiki/Prism.
- Custom components: import at top and map via
export const components.
Images
- Use
<Image />or@astrojs/image: multi-size, WebP, lazy-loading. - Set
width/height/formatto avoid shipping originals raw. - Configure remote domains allowlist for external images.
Content management practices
- Structure by language/topic/year; semantic file names.
- Tags/categories in frontmatter for filtering/search.
- Related content via slug/ID (related posts, prev/next).
- Search: generate static JSON index at build, query client-side, or use external search.