Astro + Contentful · Lesson 7 of 15 · 15 min

Connect Astro to Contentful

Start a new Astro project, store your keys in environment variables, and write a small client that fetches every entry.

1. Create the project

npm create astro@latest learn-hub -- --template minimal
cd learn-hub

Say yes to installing dependencies and to git.

2. Install the Contentful packages

npm install contentful @contentful/rich-text-html-renderer @contentful/rich-text-types
Package What it does
contentful The official JavaScript SDK for the Delivery and Preview APIs
@contentful/rich-text-html-renderer Turns a Rich text field into HTML
@contentful/rich-text-types Names for the parts of a Rich text field

3. Add environment variables

Create a .env file at the project root with the values from lesson 2:

.env

CONTENTFUL_SPACE_ID=your_space_id
CONTENTFUL_DELIVERY_TOKEN=your_delivery_token
CONTENTFUL_PREVIEW_TOKEN=your_preview_token

And a copy without secrets, so anyone cloning the repo knows what to set:

.env.example

CONTENTFUL_SPACE_ID=
CONTENTFUL_DELIVERY_TOKEN=
CONTENTFUL_PREVIEW_TOKEN=

Check that .gitignore lists .env. The minimal template includes it. Never commit .env.

None of these names start with PUBLIC_, so Astro keeps them on the server. They never reach the browser.

4. Write the Contentful client

src/lib/contentful.ts

import * as contentful from 'contentful';

/** The parts of a Contentful entry this project uses. */
export interface CFEntry {
  sys: {
    id: string;
    updatedAt: string;
    contentType: { sys: { id: string } };
  };
  fields: Record<string, any>;
}

function getClient() {
  const space = import.meta.env.CONTENTFUL_SPACE_ID;
  const accessToken = import.meta.env.CONTENTFUL_DELIVERY_TOKEN;

  if (!space || !accessToken) {
    throw new Error('Missing Contentful settings. Check your .env file.');
  }

  return contentful.createClient({
    space,
    accessToken,
    environment: import.meta.env.CONTENTFUL_ENVIRONMENT ?? 'master',
  }).withoutUnresolvableLinks;
}

/** Fetch every entry of one content type, 100 at a time. */
export async function fetchEntries(contentType: string): Promise<CFEntry[]> {
  const client = getClient();
  const entries: CFEntry[] = [];
  let total = 0;

  do {
    const res = await client.getEntries({
      content_type: contentType,
      include: 2,
      limit: 100,
      skip: entries.length,
    });
    entries.push(...(res.items as unknown as CFEntry[]));
    total = res.total;
    if (res.items.length === 0) break;
  } while (entries.length < total);

  return entries;
}

What each piece does

CFEntry describes the parts of an entry you use. fields is loose on purpose. The content collection schema in the next lesson is what checks your data.

getClient() fails with a clear message when a key is missing. That beats a confusing network error.

environment defaults to master. Lesson 13 points it somewhere else.

.withoutUnresolvableLinks drops links to things the API can’t return. Your course links to a draft lesson. With this setting the draft is simply left out of the course’s lesson list, so a half-written lesson can’t break the build.

include: 2 follows links two levels deep, so a course arrives with its lessons, and each lesson with its author.

The loop handles pagination. total says how many entries exist. The loop keeps asking, skipping the ones it already has, until it has them all.

5. Quick test

src/pages/cf-test.astro

---
import { fetchEntries } from '../lib/contentful';

const lessons = await fetchEntries('lesson');
---

<h1>{lessons.length} lessons from Contentful</h1>
<ul>
  {lessons.map((lesson) => (
    <li>
      {lesson.fields.title} ({lesson.fields.slug}) by {lesson.fields.author?.fields.name}
    </li>
  ))}
</ul>

Run npm run dev and visit localhost:4321/cf-test. You should see your two published lessons with the author’s name. Delete cf-test.astro once it works.