Astro + Contentful · Lesson 8 of 15 · 15 min

Contentful entries as content collections

Write a custom loader so authors, lessons, and courses become typed Astro collections that reference each other.

You could call fetchEntries() on every page. Instead, you’ll feed Contentful into Astro’s content collections. Then pages use getCollection() and render(), the same as they would for Markdown, and a schema checks every entry.

If you did the WordPress module in Astro from Scratch, this is the same move with a different backend.

1. Render rich text

A Rich text field arrives as JSON, not HTML. Start with the simplest converter. You’ll upgrade it in lesson 10.

src/lib/rich-text.ts

import { documentToHtmlString } from '@contentful/rich-text-html-renderer';
import type { Document } from '@contentful/rich-text-types';

export function richTextToHtml(doc?: Document): string {
  return doc ? documentToHtmlString(doc) : '';
}

2. Write the loader

src/lib/contentful-loader.ts

import type { Loader } from 'astro/loaders';
import { fetchEntries, type CFEntry } from './contentful';
import { richTextToHtml } from './rich-text';

type ContentType = 'author' | 'lesson' | 'course';

/** One function per content type. Each returns the fields the schema expects. */
const mappers: Record<ContentType, (entry: CFEntry) => Record<string, unknown>> = {
  author: ({ fields }) => ({
    name: fields.name,
    role: fields.role,
    photo: fields.photo?.fields?.file?.url
      ? `https:${fields.photo.fields.file.url}`
      : undefined,
  }),
  lesson: ({ fields }) => ({
    title: fields.title,
    summary: fields.summary,
    minutes: fields.minutes,
    author: fields.author?.sys.id,
  }),
  course: ({ fields }) => ({
    title: fields.title,
    summary: fields.summary,
    level: fields.level,
    lessons: (fields.lessons ?? []).map((lesson: CFEntry) => lesson.fields.slug),
  }),
};

export function contentfulLoader(contentType: ContentType): Loader {
  return {
    name: `contentful-${contentType}`,
    load: async ({ store, parseData, logger, generateDigest }) => {
      logger.info(`Fetching ${contentType} entries from Contentful`);
      const entries = await fetchEntries(contentType);

      store.clear();
      for (const entry of entries) {
        const id: string = entry.fields.slug ?? entry.sys.id;
        const data = await parseData({ id, data: mappers[contentType](entry) });
        store.set({
          id,
          data,
          rendered: entry.fields.body ? { html: richTextToHtml(entry.fields.body) } : undefined,
          digest: generateDigest(entry.sys.updatedAt),
        });
      }

      logger.info(`Loaded ${entries.length} ${contentType} entries`);
    },
  };
}

How it works

mappers reshape each Contentful entry into plain data. This is the one place that knows Contentful’s field names. If a field is renamed, you fix it here and nowhere else.

id is the slug when there is one, so a lesson’s URL comes from its slug. Authors have no slug, so they use Contentful’s own ID.

Links become IDs. A lesson stores its author’s ID. A course stores a list of lesson slugs. Astro turns those into real references in the next step.

https: is added because Contentful returns asset URLs that start with //.

rendered: { html } is what makes render(lesson) work later. The Rich text body becomes a <Content /> component.

generateDigest() fingerprints each entry by its last update time, so Astro can tell what changed.

3. Define the collections

src/content.config.ts

import { defineCollection, reference } from 'astro:content';
import { z } from 'astro/zod';
import { contentfulLoader } from './lib/contentful-loader';

const authors = defineCollection({
  loader: contentfulLoader('author'),
  schema: z.object({
    name: z.string(),
    role: z.string().optional(),
    photo: z.string().optional(),
  }),
});

const lessons = defineCollection({
  loader: contentfulLoader('lesson'),
  schema: z.object({
    title: z.string(),
    summary: z.string().default(''),
    minutes: z.number().default(5),
    author: reference('authors').optional(),
  }),
});

const courses = defineCollection({
  loader: contentfulLoader('course'),
  schema: z.object({
    title: z.string(),
    summary: z.string().default(''),
    level: z.enum(['Beginner', 'Intermediate', 'Advanced']).default('Beginner'),
    lessons: z.array(reference('lessons')).default([]),
  }),
});

export const collections = { authors, lessons, courses };

reference('authors') tells Astro that the value is the ID of an entry in another collection. It’s the Astro version of the Reference field you made in Contentful.

The schema is your second line of defense. Contentful’s validations stop bad content going in. The schema stops surprising content coming out. If someone adds a fourth Level in Contentful, the build fails with a clear message instead of shipping a broken page.

4. Restart and check

Restart npm run dev. The terminal shows something like:

[contentful-author] Loaded 1 author entries
[contentful-lesson] Loaded 2 lesson entries
[contentful-course] Loaded 1 course entries