To use Payload CMS with Astro, run Payload as its own app (Payload 3 lives inside a Next.js project), then pull content into Astro over Payload’s REST or GraphQL API. The cleanest pattern is a small content loader in src/content.config.ts that fetches published documents at build time, plus an afterChange hook in Payload that triggers a rebuild when an editor publishes.
This guide walks through that setup for an Astro 7 site: the architecture, the loader, rendering rich text, images, drafts and deployment.
Key Takeaways
- Payload and Astro are two separate apps. Payload is the admin and API; Astro builds the public site.
- Fetch from
/api/<collection>with awherequery anddepthto control how much related data comes back.- A custom content loader gives you typed, schema-checked Payload data through
getCollection().- Convert Lexical rich text to HTML on the Payload side or in the loader, so Astro only renders a string.
- Use an
afterChangehook to call your host’s deploy hook, or render pages on demand if content changes every minute.
How Astro and Payload CMS fit together
Payload is an open-source, TypeScript-first headless CMS. Since version 3 it installs into a Next.js app and serves the admin panel and API from there. It needs a database (MongoDB, Postgres or SQLite through its adapters) and a Node.js host.
Astro doesn’t need to know any of that. From Astro’s point of view, Payload is an HTTP API that returns JSON:
| Piece | Runs where | Job |
|---|---|---|
| Payload (Next.js app) | Node.js host with a database | Admin UI, auth for editors, REST and GraphQL API |
| Astro site | Static host or adapter | Fetches published content, renders pages |
| Deploy hook | Your host (Netlify, Vercel, Cloudflare) | Rebuilds Astro when content changes |
You can keep both apps in one monorepo, but they deploy separately. If you are still deciding whether an API-based CMS like Payload is right for your site, read choosing a headless CMS for Astro first. Payload is a strong fit when developers want to define the content model in code and own the database.
Query the Payload REST API
Every Payload collection gets REST endpoints automatically. A posts collection is available at /api/posts, and the response is paginated:
{
"docs": [{ "id": "6721", "title": "Hello", "slug": "hello", "_status": "published" }],
"totalDocs": 42,
"limit": 10,
"totalPages": 5,
"page": 1,
"hasNextPage": true
}
Three query parameters do most of the work:
wherefilters documents, written in bracket syntax:where[_status][equals]=published.depthcontrols how deeply relationships and uploads are populated.depth=1turns an image ID into the full media document with itsurl.limitandpagehandle pagination. Payload’s default limit is 10, so always set it.
Try it in the terminal before writing any Astro code:
curl "https://cms.example.com/api/posts?where[_status][equals]=published&depth=1&limit=100"
The _status field only exists when drafts are enabled on the collection. If you don’t use drafts, drop that filter.
Load Payload posts with a content loader
Fetching in page frontmatter works, but a content loader is better for a build-time site. It runs once per build, validates every document against a schema, and gives every page typed data through getCollection(). The content layer loaders guide explains the loader API in depth.
// src/loaders/payload.ts
import type { Loader } from 'astro/loaders';
export function payloadLoader(opts: { url: string; collection: string; apiKey?: string }): Loader {
return {
name: 'payload-loader',
async load({ store, parseData, generateDigest, logger }) {
const headers: Record<string, string> = {};
if (opts.apiKey) headers.Authorization = `users API-Key ${opts.apiKey}`;
store.clear();
let page = 1;
let hasNextPage = true;
while (hasNextPage) {
const query = `where[_status][equals]=published&depth=1&limit=100&page=${page}`;
const res = await fetch(`${opts.url}/api/${opts.collection}?${query}`, { headers });
if (!res.ok) throw new Error(`Payload returned ${res.status} for ${opts.collection}`);
const json = await res.json();
for (const doc of json.docs) {
const data = await parseData({ id: doc.slug, data: doc });
store.set({ id: doc.slug, data, digest: generateDigest(doc) });
}
hasNextPage = json.hasNextPage;
page += 1;
}
logger.info(`Loaded ${store.keys().length} ${opts.collection}`);
},
};
}
Register it as a collection with a schema that matches your Payload fields:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { payloadLoader } from './loaders/payload';
const posts = defineCollection({
loader: payloadLoader({
url: import.meta.env.PAYLOAD_URL,
collection: 'posts',
apiKey: import.meta.env.PAYLOAD_API_KEY,
}),
schema: z.object({
title: z.string(),
slug: z.string(),
excerpt: z.string().optional(),
publishedAt: z.coerce.date(),
contentHtml: z.string(),
heroImage: z.object({ url: z.string(), alt: z.string().optional() }).nullable().optional(),
}),
});
export const collections = { posts };
The API key header uses Payload’s format: the auth collection’s slug, then API-Key, then the key. Enable useAPIKey on your users collection to issue keys. Only send a key if your collection’s read access requires one; public published posts often don’t. Keep PAYLOAD_URL and the key in .env, as covered in the environment variables guide.
Render Payload rich text in Astro
Payload 3 uses the Lexical editor, which stores rich text as a JSON tree, not HTML. You have two practical options.
Convert in Payload. Add a virtual or hook-populated contentHtml field to the collection that runs Lexical’s HTML converter from @payloadcms/richtext-lexical before the document is returned. Astro then receives a ready HTML string, which is what the schema above expects. This keeps the Astro side simple and works for any consumer of the API.
Convert in Astro. Fetch the raw Lexical JSON and walk the tree yourself in a component. This gives you full control over markup (custom blocks become Astro components), but you have to handle every node type you use.
For most marketing sites and blogs, converting in Payload is less work. Rendering the HTML in Astro is then one line:
---
// src/pages/blog/[slug].astro
import { getCollection, getEntry } 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 } }));
}
const post = await getEntry('posts', Astro.params.slug);
if (!post) throw new Error(`Missing post ${Astro.params.slug}`);
const { title, publishedAt, contentHtml, heroImage } = post.data;
---
<BaseLayout title={title}>
<article>
<h1>{title}</h1>
<time datetime={publishedAt.toISOString()}>{publishedAt.toLocaleDateString('en-US')}</time>
{heroImage && <img src={heroImage.url} alt={heroImage.alt ?? ''} width="1200" height="630" />}
<Fragment set:html={contentHtml} />
</article>
</BaseLayout>
set:html injects the string without escaping, so only use it with content from your own CMS, where editors are trusted.
Images from Payload uploads
Upload collections in Payload return a url, plus sizes if you configured image sizes. If Payload stores files locally, that URL is relative to the Payload server, so prefix it with PAYLOAD_URL in the loader. If you use a storage adapter such as S3, the URL already points at the bucket.
To run remote images through astro:assets and <Image />, authorize the domain:
// astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
image: {
remotePatterns: [{ protocol: 'https', hostname: 'cms.example.com' }],
},
});
Then <Image src={heroImage.url} alt={heroImage.alt} width={1200} height={630} /> produces optimized files at build time. For large libraries, Payload’s own sizes are often enough and keep builds fast.
Rebuild Astro when editors publish
A static Astro site only shows new content after a build. Payload’s collection hooks make this automatic. Create a deploy hook URL at your host, then call it after a published change:
// payload: src/collections/Posts.ts
import type { CollectionConfig } from 'payload';
export const Posts: CollectionConfig = {
slug: 'posts',
versions: { drafts: true },
hooks: {
afterChange: [
async ({ doc }) => {
if (doc._status === 'published' && process.env.DEPLOY_HOOK_URL) {
await fetch(process.env.DEPLOY_HOOK_URL, { method: 'POST' });
}
return doc;
},
],
},
fields: [
{ name: 'title', type: 'text', required: true },
{ name: 'slug', type: 'text', required: true, unique: true },
{ name: 'publishedAt', type: 'date' },
],
};
Add an afterDelete hook too, or removed posts stay live until the next build. If editors publish many times an hour, debounce the hook or rebuild on a schedule.
Drafts and preview
Payload’s draft system stores unpublished versions. Your build only fetches _status: published, so drafts never leak. For a preview link, render one route on demand with an adapter and fetch with draft=true and an API key:
// src/pages/preview/[slug].astro (frontmatter)
export const prerender = false;
const res = await fetch(
`${import.meta.env.PAYLOAD_URL}/api/posts?where[slug][equals]=${Astro.params.slug}&draft=true&depth=1`,
{ headers: { Authorization: `users API-Key ${import.meta.env.PAYLOAD_API_KEY}` } },
);
Protect that route, for example with basic auth in middleware, and set Payload’s admin.livePreview or preview URL to point at it. The middleware guide shows how to guard a path.
When to render on demand instead
Build-time loading suits blogs, docs and marketing pages. If content must appear within seconds, or you have tens of thousands of documents, consider rendering on demand with an adapter. Astro’s live collections (defineLiveCollection() in src/live.config.ts) fetch from the CMS at request time while keeping the getLiveEntry() API typed. Pair that with HTTP caching so Payload isn’t hit on every request.
A hybrid is common: prerender the blog index and posts, and render only search or member pages on demand.
Deploying both apps
Payload needs a Node.js server and a database; a static host can’t run it. Typical setups put Payload on a VPS, a container platform or Vercel, with Postgres or MongoDB alongside. The Astro site can go anywhere static, such as Cloudflare Pages or Netlify, as described in deploying to static hosts.
If you’re building a SaaS or product site around Payload, the marketing side doesn’t have to start from zero. The Astro technology themes give you finished landing, pricing and blog pages that you can point at a Payload loader instead of local Markdown.
The Payload REST API docs and Astro’s content loader reference are the references for the two halves of this setup.
FAQ
Can Payload CMS run inside an Astro project?
Not as a first-class integration. Payload 3 is built on Next.js and runs its admin and API from a Next.js app. Run Payload separately, or in the same monorepo as a second app, and have Astro consume its REST or GraphQL API.
Should I use the Payload REST API or GraphQL with Astro?
Either works. REST needs no extra client and the depth parameter covers most relationship needs, so it’s the simpler default for a content loader. Choose GraphQL if you want to request exact fields across several collections in one query.
Is Payload CMS free to use with Astro?
Payload is open source under the MIT licence, so you can self-host it at no licence cost. You still pay for the Node.js hosting and database it runs on. Check Payload’s site for its current hosted offering if you don’t want to run it yourself.
How do I show Payload drafts in Astro?
Render a preview route on demand with an adapter, fetch the document with draft=true and an API key, and protect the route. Your production build keeps filtering on _status equal to published, so drafts never appear on the public site.
Does Astro need SSR to use Payload?
No. A content loader fetches everything at build time and Astro outputs static HTML. You only need an adapter for draft previews, member areas or content that must update without a rebuild.