To use Strapi with Astro, create a content type in Strapi, give Astro a read-only API token, and fetch entries from Strapi’s REST API (for example /api/articles?populate=cover) inside a content loader. Astro builds static pages from the data, and a Strapi webhook calls your host’s deploy hook so the site rebuilds when an editor publishes. Strapi runs the admin panel and database; Astro only reads the API.
This guide sets that up with Strapi 5 and Astro 7: tokens, a typed loader, media URLs, drafts and rebuilds.
Key Takeaways
- Strapi is an open-source, self-hostable Node.js headless CMS with REST and GraphQL APIs.
- Strapi 5 returns flat entries (no
attributeswrapper) with adocumentIdfor each document.- Relations and media are not returned unless you ask for them with
populate.- A custom content loader turns Strapi entries into typed collections you read with
getCollection().- Rebuild on
entry.publishandentry.unpublishwith a webhook to your host’s deploy hook.
How Astro and Strapi fit together
Strapi is an open-source headless CMS written in Node.js. You define content types in its admin panel (or in code), and Strapi generates REST endpoints, an optional GraphQL API, roles and permissions, and a media library. You can self-host it with SQLite, PostgreSQL or MySQL, or use Strapi Cloud.
| Piece | Runs where | Job |
|---|---|---|
| Strapi | Your server, a container, or Strapi Cloud | Admin, database, media, API |
| Astro site | Static host, or an adapter for on-demand pages | Fetches published entries, renders HTML |
| Webhook | Strapi | Calls the deploy hook when content changes |
The split keeps your public site static and cheap to host while editors get a full admin. It also means Strapi can sit behind a firewall or on a small server, since only the build machine talks to it. If you’re comparing options first, read our headless CMS guide for Astro. Strapi fits teams that want an open-source CMS they host themselves, with a visual content-type builder.
One thing to check before you start: this guide uses Strapi 5. Strapi 4 wrapped every entry in data.attributes and used numeric id values; Strapi 5 flattened the response and added a string documentId. Code written for one version needs small changes for the other.
Create the content type and API token
In the Strapi admin, open the Content-Type Builder and create a collection type article with:
title(Text)slug(UID, attached totitle)excerpt(Text, long)body(Rich text (Markdown))cover(Media, single image)
Leave Draft & Publish enabled so editors can save drafts without them going live. The Markdown rich text field is the easiest to render in Astro; Strapi’s newer “Rich text (Blocks)” field returns JSON blocks, which need a renderer.
Then go to Settings, API Tokens, and create a token with type Read-only. Read-only tokens can call find and findOne on every content type and nothing else. Put the URL and token in .env:
# .env
STRAPI_URL=https://cms.example.com
STRAPI_TOKEN=your-read-only-token
Test it from the terminal:
curl -H "Authorization: Bearer $STRAPI_TOKEN" \
"$STRAPI_URL/api/articles?fields[0]=title&fields[1]=slug&pagination[pageSize]=5"
You should see a JSON object with a data array and a meta.pagination object. If you get 403, the token lacks access; if you get 404, check the plural API ID of your content type.
Write a small Strapi client
Strapi’s REST API is plain HTTP, so fetch is enough. This helper adds the token, builds query strings and pages through results:
// src/lib/strapi.ts
const base = import.meta.env.STRAPI_URL;
const token = import.meta.env.STRAPI_TOKEN;
export interface StrapiMedia {
url: string;
alternativeText: string | null;
width: number;
height: number;
}
export interface Article {
id: number;
documentId: string;
title: string;
slug: string;
excerpt: string | null;
body: string;
cover: StrapiMedia | null;
publishedAt: string;
updatedAt: string;
}
export async function strapiFetch<T>(path: string, params: Record<string, string> = {}) {
const url = new URL(`/api/${path}`, base);
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!res.ok) throw new Error(`Strapi ${res.status} for ${url.pathname}`);
return (await res.json()) as { data: T; meta: { pagination?: { pageCount: number } } };
}
export async function strapiFindAll<T>(path: string, params: Record<string, string> = {}) {
const all: T[] = [];
let page = 1;
let pageCount = 1;
do {
const res = await strapiFetch<T[]>(path, {
...params,
'pagination[page]': String(page),
'pagination[pageSize]': '100',
});
all.push(...res.data);
pageCount = res.meta.pagination?.pageCount ?? 1;
page++;
} while (page <= pageCount);
return all;
}
export function mediaUrl(url: string) {
return url.startsWith('http') ? url : new URL(url, base).href;
}
Strapi caps pageSize at 100 by default (the api.rest.maxLimit setting), so the loop matters once you pass 100 entries. mediaUrl() handles the difference between the local upload provider, which returns paths like /uploads/cover.jpg, and cloud providers such as S3 or Cloudinary, which return full URLs.
Load Strapi entries with a content loader
A content loader fetches during the build, validates each entry and stores it, so pages read it with getCollection():
// src/loaders/strapi.ts
import type { Loader } from 'astro/loaders';
import { strapiFindAll, mediaUrl, type Article } from '../lib/strapi';
export function strapiArticles(): Loader {
return {
name: 'strapi-articles',
async load({ store, parseData, renderMarkdown, generateDigest, logger }) {
const articles = await strapiFindAll<Article>('articles', {
populate: 'cover',
sort: 'publishedAt:desc',
});
store.clear();
for (const a of articles) {
const data = await parseData({
id: a.slug,
data: {
title: a.title,
excerpt: a.excerpt ?? '',
publishedAt: a.publishedAt,
cover: a.cover ? mediaUrl(a.cover.url) : null,
coverAlt: a.cover?.alternativeText ?? '',
},
});
store.set({
id: a.slug,
data,
rendered: await renderMarkdown(a.body ?? ''),
digest: generateDigest(a.updatedAt + a.documentId),
});
}
logger.info(`Loaded ${articles.length} articles from Strapi`);
},
};
}
renderMarkdown() runs the Markdown field through Astro’s own Markdown pipeline, so headings get IDs and code blocks get syntax highlighting, the same as local .md files. Register it:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { strapiArticles } from './loaders/strapi';
const articles = defineCollection({
loader: strapiArticles(),
schema: z.object({
title: z.string(),
excerpt: z.string(),
publishedAt: z.coerce.date(),
cover: z.string().nullable(),
coverAlt: z.string(),
}),
});
export const collections = { articles };
The REST API returns only published entries unless you pass status=draft, so drafts never leak into the build. For background on loaders and schemas, see our content loaders guide and the Content Collections docs page.
Render article pages and media
---
// src/pages/blog/[slug].astro
import { getCollection, render } from 'astro:content';
import { Image } from 'astro:assets';
import BaseLayout from '../../layouts/BaseLayout.astro';
export async function getStaticPaths() {
const articles = await getCollection('articles');
return articles.map((article) => ({ params: { slug: article.id }, props: { article } }));
}
const { article } = Astro.props;
const { Content } = await render(article);
const { title, cover, coverAlt, publishedAt } = article.data;
---
<BaseLayout title={title}>
<article>
<h1>{title}</h1>
<time datetime={publishedAt.toISOString()}>{publishedAt.toLocaleDateString('en-US')}</time>
{cover && <Image src={cover} alt={coverAlt} width={1200} height={630} />}
<Content />
</article>
</BaseLayout>
Strapi doesn’t transform images on request, though it does generate thumbnail, small, medium and large variants on upload (in cover.formats). Using <Image /> from astro:assets lets Astro resize and convert the original at build time. Allow the Strapi host first:
// astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
site: 'https://www.example.com',
image: {
domains: ['cms.example.com'],
},
});
If media lives on S3 or Cloudinary, add that domain instead. See our Astro image component guide for widths, formats and densities.
Rebuild when content changes
In the Strapi admin, open Settings, Webhooks, and create one:
- URL: your host’s deploy hook from Netlify, Vercel or Cloudflare Pages.
- Events: Entry publish and unpublish, Entry delete, and Media create, update and delete if images change independently.
- Headers: none needed for most deploy hooks.
With Draft & Publish on, choose publish and unpublish rather than create and update, otherwise every draft save triggers a build. Keep the deploy hook URL secret; anyone who has it can start builds. Our Astro deployment guide covers deploy hooks for each host.
Preview drafts
To let editors check a draft, add one on-demand route that asks Strapi for the draft version:
---
// src/pages/preview/[slug].astro
import { marked } from 'marked';
import { strapiFetch, type Article } from '../../lib/strapi';
export const prerender = false;
if (Astro.url.searchParams.get('secret') !== import.meta.env.PREVIEW_SECRET) {
return new Response('Not found', { status: 404 });
}
const res = await strapiFetch<Article[]>('articles', {
'filters[slug][$eq]': Astro.params.slug ?? '',
status: 'draft',
populate: 'cover',
});
const article = res.data[0];
if (!article) return new Response('Not found', { status: 404 });
---
<html lang="en">
<head><meta name="robots" content="noindex" /><title>Preview: {article.title}</title></head>
<body>
<h1>{article.title}</h1>
<Fragment set:html={await marked.parse(article.body ?? '')} />
</body>
</html>
marked (installed with npm install marked) converts Markdown at request time, since renderMarkdown() exists only inside loaders. Read-only tokens can read drafts with status=draft. This route needs an adapter, while the rest of the site stays prerendered. Strapi 5 has a Preview feature in the admin where you configure the preview URL per content type, so editors get a button that opens this route.
REST or GraphQL
Strapi’s GraphQL plugin (@strapi/plugin-graphql) adds a /graphql endpoint. GraphQL is handy when one page needs several related content types with exact fields. REST with populate and fields covers most Astro sites and needs no extra plugin. Either way, the loader is the only file that changes.
For the site itself, an Astro blog theme gives you finished post and listing templates; you replace its local posts with the Strapi collection and keep the layout.
FAQ
Is there an official Astro integration for Strapi?
No first-party package exists. You read Strapi’s REST or GraphQL API with fetch or a client library, usually in a content loader. Astro’s docs have a Strapi guide that shows the same pattern.
Why are images and relations missing from Strapi’s API response?
Strapi doesn’t return relations, media, components or dynamic zones unless you populate them. Add populate=cover for one field, populate=* for one level of everything, or a nested populate object for deeper relations.
Can I host Strapi and Astro on the same server?
You can, but they’re separate processes. Strapi needs a Node.js server and a database, while the Astro site is usually static files on a CDN. Many teams host Strapi on a small VPS or Strapi Cloud and deploy Astro to Netlify, Vercel or Cloudflare Pages.
Does Astro with Strapi work for a static site?
Yes. Fetch everything at build time, deploy the static output, and rebuild through a webhook on publish. Strapi doesn’t need to be reachable by visitors at all, only by the build.
What changed between Strapi 4 and Strapi 5 for Astro code?
Strapi 5 removed the data.attributes wrapper, so fields sit directly on each entry, and added a string documentId used for document operations. Drafts are requested with status=draft instead of publicationState=preview. Update your types and field access when you upgrade.