To use Contentful with Astro, install the contentful SDK, create a client with your space ID and Content Delivery API token, and fetch entries with client.getEntries() inside a content loader. Astro builds static pages from those entries, and a Contentful webhook calls your host’s deploy hook so the site rebuilds whenever an editor publishes. Contentful stores and edits the content; Astro only reads it.
This guide sets that up on an Astro 7 site: the content model, a typed loader, rich text, images, draft previews and rebuilds.
Key Takeaways
- Contentful is a hosted headless CMS with a Delivery API (published content) and a Preview API (drafts).
- Fetch entries in a custom content loader so you can use
getCollection()and typed schemas.- Render rich text fields with
@contentful/rich-text-html-rendererand pass the HTML torendered.- Resize images with URL parameters on
images.ctfassets.net, such asw,handfm=webp.- Rebuild on publish with a Contentful webhook pointed at your host’s deploy hook.
How Astro and Contentful fit together
Contentful is a hosted, API-first content platform. Editors work in the Contentful web app; developers define content types (fields and validations) and read entries through REST or GraphQL APIs. There’s no server for you to run.
| Piece | Runs where | Job |
|---|---|---|
| Contentful space | Contentful’s cloud | Content model, editing, assets, APIs |
| Astro site | Static host, or an adapter for on-demand pages | Fetches published entries, renders HTML |
| Webhook | Contentful | Calls the deploy hook when entries change |
Contentful has separate tokens for its two read APIs. The Content Delivery API (cdn.contentful.com) returns published entries only and is served from a CDN. The Content Preview API (preview.contentful.com) returns drafts and changes too. Both are read-only, which makes them safe for build servers.
If you’re still choosing a CMS, our headless CMS guide for Astro compares Contentful with Sanity, Storyblok, Directus and Git-based options. Contentful suits teams that want a managed service with roles, locales and workflows, and are fine with per-seat pricing as they grow. Check Contentful’s current plans before you commit.
Model the content and create tokens
In the Contentful web app, create a content type called blogPost with these fields:
title(Short text)slug(Short text, unique)excerpt(Long text)body(Rich text)heroImage(Media, one image)publishDate(Date and time)
Then open Settings, API keys, and add an API key. Copy the space ID, the Content Delivery API access token and the Content Preview API access token into .env:
# .env
CONTENTFUL_SPACE_ID=abc123xyz
CONTENTFUL_DELIVERY_TOKEN=your-delivery-token
CONTENTFUL_PREVIEW_TOKEN=your-preview-token
Add the same variables in your host’s environment settings. You can declare them in astro.config.mjs with envField so the build fails early when one is missing; our environment variables guide shows how.
Install the SDK and create a client
npm install contentful @contentful/rich-text-html-renderer
Create one client module. The preview flag switches host and token, which you’ll use later for draft previews:
// src/lib/contentful.ts
import { createClient } from 'contentful';
export function contentfulClient(preview = false) {
return createClient({
space: import.meta.env.CONTENTFUL_SPACE_ID,
accessToken: preview
? import.meta.env.CONTENTFUL_PREVIEW_TOKEN
: import.meta.env.CONTENTFUL_DELIVERY_TOKEN,
host: preview ? 'preview.contentful.com' : 'cdn.contentful.com',
});
}
Both read APIs are rate limited per space, but a build makes only a handful of requests, so limits rarely matter for static sites.
Load Contentful entries with a content loader
You can call getEntries() in each page’s frontmatter, but a content loader fetches once per build, validates every entry against a schema, and gives you getCollection() everywhere. Here’s a loader for the blogPost type:
// src/loaders/contentful.ts
import type { Loader } from 'astro/loaders';
import { documentToHtmlString } from '@contentful/rich-text-html-renderer';
import { contentfulClient } from '../lib/contentful';
export function contentfulPosts(): Loader {
return {
name: 'contentful-posts',
async load({ store, parseData, generateDigest, logger }) {
const client = contentfulClient();
const res = await client.withoutUnresolvableLinks.getEntries({
content_type: 'blogPost',
order: ['-fields.publishDate'],
include: 2,
limit: 1000,
});
store.clear();
for (const item of res.items) {
const f = item.fields as any;
const image = f.heroImage?.fields;
const data = await parseData({
id: f.slug,
data: {
title: f.title,
excerpt: f.excerpt ?? '',
publishDate: f.publishDate,
image: image ? `https:${image.file.url}` : null,
imageAlt: image?.description ?? '',
},
});
store.set({
id: f.slug,
data,
rendered: { html: documentToHtmlString(f.body) },
digest: generateDigest(item.sys.updatedAt + item.sys.id),
});
}
logger.info(`Loaded ${res.items.length} of ${res.total} Contentful posts`);
},
};
}
A few details matter here:
include: 2resolves linked entries and assets two levels deep, soheroImage.fieldsis filled in.withoutUnresolvableLinksdrops links to unpublished or deleted entries instead of leaving broken link objects.limitmaxes out at 1,000 per request. Above that, loop withskipuntil you’ve readres.totalitems.- Asset URLs start with
//, so prefixhttps:before using them.
Register the loader with a schema:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { contentfulPosts } from './loaders/contentful';
const posts = defineCollection({
loader: contentfulPosts(),
schema: z.object({
title: z.string(),
excerpt: z.string(),
publishDate: z.coerce.date(),
image: z.string().nullable(),
imageAlt: z.string(),
}),
});
export const collections = { posts };
If you’d rather type the raw entries, the SDK accepts a generic skeleton type (client.getEntries<BlogPostSkeleton>()), and cf-content-types-generator can generate those types from your space. The loader schema above already gives pages typed data, so it’s optional. For more on how loaders work, see our content loaders guide and the Content Collections docs page.
Render rich text and images
Because the loader stores HTML in rendered, a page can use render() and <Content /> like any Markdown collection:
---
// src/pages/blog/[slug].astro
import { getCollection, render } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';
export async function getStaticPaths() {
const posts = await getCollection('posts');
return posts.map((post) => ({ params: { slug: post.id }, props: { post } }));
}
const { post } = Astro.props;
const { Content } = await render(post);
const { title, image, imageAlt, publishDate } = post.data;
---
<BaseLayout title={title}>
<article>
<h1>{title}</h1>
<time datetime={publishDate.toISOString()}>{publishDate.toLocaleDateString('en-US')}</time>
{image && (
<img
src={`${image}?w=1200&h=630&fit=fill&fm=webp&q=80`}
alt={imageAlt}
width="1200"
height="630"
/>
)}
<Content />
</article>
</BaseLayout>
The Contentful Images API resizes and converts on request: w and h set size, fit controls cropping, fm picks the format (webp, avif, jpg, png) and q sets quality. Contentful caches the results on its CDN, so this is usually enough without Astro’s image pipeline. If you prefer <Image /> from astro:assets, add images.ctfassets.net to image.domains in astro.config.mjs.
documentToHtmlString() renders paragraphs, headings, lists, quotes and links. Embedded entries and assets inside rich text need custom renderers, which you pass as the second argument:
// src/lib/rich-text.ts
import { documentToHtmlString } from '@contentful/rich-text-html-renderer';
import { BLOCKS } from '@contentful/rich-text-types';
export function richTextToHtml(doc: any) {
return documentToHtmlString(doc, {
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: (node) => {
const file = node.data.target.fields?.file;
const alt = node.data.target.fields?.description ?? '';
return file ? `<img src="https:${file.url}?w=1000&fm=webp" alt="${alt}" loading="lazy" />` : '';
},
},
});
}
@contentful/rich-text-types is installed as a dependency of the renderer; add it to package.json explicitly if you import from it.
Rebuild when editors publish
A static build only shows new content after the next build. In Contentful, open Settings, Webhooks, and add one:
- URL: your host’s deploy hook (Netlify, Vercel and Cloudflare Pages all generate one).
- Method:
POST. - Triggers: Entry publish, unpublish and delete; Asset publish, unpublish and delete.
- Filter (optional): limit to the
masterenvironment so sandbox edits don’t rebuild production.
Every publish now starts a build. If editors publish many entries at once, some hosts queue or cancel overlapping builds, which is fine because the last build reads everything. Keep the deploy hook URL private; anyone with it can trigger builds. The Astro deployment guide covers deploy hooks for each host.
Preview drafts
Editors want to see a draft before they publish. The usual setup is one on-demand route that reads from the Preview API:
---
// src/pages/preview/[slug].astro
import { contentfulClient } from '../../lib/contentful';
import { richTextToHtml } from '../../lib/rich-text';
export const prerender = false;
if (Astro.url.searchParams.get('secret') !== import.meta.env.PREVIEW_SECRET) {
return new Response('Not found', { status: 404 });
}
const client = contentfulClient(true);
const res = await client.getEntries({
content_type: 'blogPost',
'fields.slug': Astro.params.slug,
limit: 1,
});
const entry = res.items[0];
if (!entry) return new Response('Not found', { status: 404 });
const f = entry.fields as any;
---
<html lang="en">
<head><meta name="robots" content="noindex" /><title>Preview: {f.title}</title></head>
<body>
<h1>{f.title}</h1>
<Fragment set:html={richTextToHtml(f.body)} />
</body>
</html>
This route needs an adapter (Node, Netlify, Vercel or Cloudflare). The rest of the site stays static. In Contentful, open Settings, Content preview, and set the preview URL to https://www.example.com/preview/{entry.fields.slug}/?secret=... so editors get an “Open preview” button. The Astro SSR guide explains how mixing prerendered and on-demand routes works.
Locales and GraphQL
Contentful supports multiple locales per space. Pass locale: 'de-DE' to getEntries() for one locale, or locale: '*' to get every locale’s values at once and build localized routes. Pair it with Astro’s i18n routing so each locale gets its own URL prefix.
If you want the front end done before you wire up Contentful, an Astro blog theme gives you the post layout, listing pages and RSS feed; you swap its local Markdown collection for the Contentful loader above and keep the templates.
Contentful also has a GraphQL Content API at graphql.contentful.com. It’s useful when you want precise field selection across linked entries in one query. The REST SDK is simpler to start with, and the loader pattern works the same with either.
FAQ
Does Astro have an official Contentful integration?
No, there’s no first-party @astrojs/contentful package. You use Contentful’s own contentful JavaScript SDK, either directly in pages or inside a content loader, and Astro’s Contentful guide documents that approach.
Is Contentful free to use with Astro?
Contentful has a free plan with limits on users, content types and API usage, and paid plans above that. Astro itself is free and open source. Check Contentful’s pricing page for current limits, since they change.
Can I use Contentful with a fully static Astro site?
Yes. Fetch entries at build time with a loader or getStaticPaths(), deploy the static output, and trigger a rebuild from a Contentful webhook when content changes. Only the draft preview route needs an adapter.
How do I render Contentful rich text in Astro?
Convert the rich text document to HTML with documentToHtmlString() from @contentful/rich-text-html-renderer, then output it with set:html or store it as rendered.html in a content loader. Add renderNode handlers for embedded entries and assets.
Why are some linked entries missing in my Astro build?
Links resolve only to published entries and only as deep as the include parameter allows, which defaults to 1. Raise include (up to 10), make sure the linked entries are published, and use withoutUnresolvableLinks so missing links are dropped instead of breaking your templates.