🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro Directus Guide: Load, Render and Rebuild Content

Connect Astro and Directus: query items with the Directus SDK in a content loader, render images from the assets endpoint, handle drafts and rebuild with Flows.

#Astro#Directus#Headless CMS#Content Layer

To use Directus with Astro, install @directus/sdk, create a client with createDirectus(url).with(rest()), and fetch published items with readItems() inside a content loader. Astro then builds static pages from that data, and a Directus Flow calls your host’s deploy hook so the site rebuilds whenever an editor publishes. Directus manages the database and admin; Astro only reads its API.

This guide sets that up on an Astro 7 site, including permissions, images, drafts, previews and on-demand rendering.

Key Takeaways

  • Directus wraps a SQL database (Postgres, MySQL, SQLite and others) with an admin app and REST and GraphQL APIs.
  • Use the official @directus/sdk with rest() and, for private collections, staticToken().
  • A custom content loader turns Directus items into typed entries you read with getCollection().
  • Serve images through /assets/<file-id> with transform parameters such as width and format.
  • Trigger rebuilds with a Directus Flow on item create, update and delete.

How Astro and Directus fit together

Directus is an open data platform: point it at a SQL database and it gives you an admin UI, roles and permissions, file storage and an API for every table. As a headless CMS it’s popular with teams who want their content in a normal relational database they can query directly.

Astro sits in front as the public site:

Piece Runs where Job
Directus Docker, a Node.js server, or Directus Cloud Admin, database, files, API
Astro site Static host, or an adapter for on-demand pages Fetches published items, renders HTML
Directus Flow Inside Directus Calls the deploy hook when content changes

If you’re comparing Directus with other options, start with choosing a headless CMS for Astro. Directus stands out when your content is relational (products, locations, authors, categories) or shared with other apps.

Directus is source-available under a Business Source License, with free use for smaller organizations and a commercial licence above a revenue threshold. Read the current licence terms on the Directus site before you self-host it for a larger company.

Set up the collection and permissions

Create a posts collection in the Directus admin with fields like title, slug, summary, content (WYSIWYG or Markdown), cover (an image field), date_published and the built-in status field (published, draft, archived).

Then decide how Astro authenticates:

  • Public read. In Settings, Access Policies, give the Public policy read access to posts with a filter of status equals published. Astro needs no token.
  • Token read. Create a user for the site with a read-only policy, generate a static token for it, and send it from Astro. Use this if any data should not be public.

Token access is the safer default, because it lets you expose drafts only to preview routes later. Check the result with curl:

curl -H "Authorization: Bearer $DIRECTUS_TOKEN" \
  "https://cms.example.com/items/posts?filter[status][_eq]=published&fields=title,slug&limit=5"

Install the Directus SDK

npm install @directus/sdk

Create one client module and type it with your schema so readItems() knows the field names:

// src/lib/directus.ts
import { createDirectus, rest, staticToken } from '@directus/sdk';

export interface Post {
  id: number;
  status: 'published' | 'draft' | 'archived';
  title: string;
  slug: string;
  summary: string | null;
  content: string;
  cover: string | null;
  date_published: string;
}

interface Schema {
  posts: Post[];
}

export const directus = createDirectus<Schema>(import.meta.env.DIRECTUS_URL)
  .with(staticToken(import.meta.env.DIRECTUS_TOKEN))
  .with(rest());

Keep DIRECTUS_URL and DIRECTUS_TOKEN in .env and in your host’s settings. The Astro environment variables guide shows how to declare them with astro:env so a missing value fails the build early.

Load Directus items with a content loader

Fetching in each page’s frontmatter works, but a content loader fetches once per build and validates every item. Here’s a loader for any Directus collection:

// src/loaders/directus.ts
import type { Loader } from 'astro/loaders';
import { readItems } from '@directus/sdk';
import { directus } from '../lib/directus';

export function directusPosts(): Loader {
  return {
    name: 'directus-posts',
    async load({ store, parseData, generateDigest, logger }) {
      const items = await directus.request(
        readItems('posts', {
          filter: { status: { _eq: 'published' } },
          fields: ['id', 'title', 'slug', 'summary', 'content', 'cover', 'date_published'],
          sort: ['-date_published'],
          limit: -1,
        }),
      );

      store.clear();
      for (const item of items) {
        const data = await parseData({ id: item.slug, data: item });
        store.set({
          id: item.slug,
          data,
          rendered: { html: item.content },
          digest: generateDigest(item),
        });
      }
      logger.info(`Loaded ${items.length} posts from Directus`);
    },
  };
}

limit: -1 returns every item. For very large collections, page through with limit and page instead so one request doesn’t time out. Register the loader with a schema:

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { directusPosts } from './loaders/directus';

const posts = defineCollection({
  loader: directusPosts(),
  schema: z.object({
    title: z.string(),
    slug: z.string(),
    summary: z.string().nullable(),
    cover: z.string().nullable(),
    date_published: z.coerce.date(),
  }),
});

export const collections = { posts };

Passing rendered: { html } lets pages use render() and <Content />. If your content field is Markdown rather than WYSIWYG HTML, call the loader context’s renderMarkdown() on it first. The content loaders guide covers both cases.

Render pages and Directus images

---
// 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 assets = `${import.meta.env.DIRECTUS_URL}/assets`;
---
<BaseLayout title={post.data.title}>
  <article>
    <h1>{post.data.title}</h1>
    {post.data.cover && (
      <img
        src={`${assets}/${post.data.cover}?width=1200&height=630&fit=cover&format=webp`}
        alt=""
        width="1200"
        height="630"
      />
    )}
    <Content />
  </article>
</BaseLayout>

Image fields store a file ID. The /assets/<id> endpoint serves the file and resizes it on request with width, height, fit, quality and format. Directus caches the transformed files, so this is often enough without Astro’s image pipeline. If assets are private, the image URL needs an access token, which you don’t want in public HTML; make the folder public or download images in the loader instead.

To use <Image /> from astro:assets, add the Directus domain to image.remotePatterns in astro.config.mjs.

Rebuild when content changes

A static build only shows new content after a rebuild. In Directus, create a Flow:

  1. Trigger: Event Hook, type Action (non-blocking), scope items.create, items.update and items.delete, collection posts.
  2. Operation: Webhook / Request URL, method POST, URL = your host’s deploy hook (Netlify, Vercel and Cloudflare Pages all provide one).

Every save now starts a build. If editors save often, add a condition step that only continues when status is published, or rebuild on a schedule instead. The deploy hook URL is a secret; anyone with it can trigger builds.

Drafts and live preview

Drafts never appear in the build because the loader filters on status. For previews, render one route on demand with an adapter, fetch the item with a token that can read drafts, and protect the route:

// src/pages/preview/[slug].astro (frontmatter)
import { readItems } from '@directus/sdk';
import { directus } from '../../lib/directus';

export const prerender = false;

const [post] = await directus.request(
  readItems('posts', { filter: { slug: { _eq: Astro.params.slug } }, limit: 1 }),
);
if (!post) return Astro.redirect('/404/');

In the Directus collection settings, set the Preview URL to https://www.example.com/preview/{{slug}}/ so editors get a preview pane next to the form. Guard the route with a secret query parameter or basic auth in Astro middleware.

Build-time or on-demand

Build-time loading suits blogs, documentation and marketing pages. Render on demand when inventory, prices or listings change every few minutes, or when there are too many items to rebuild quickly. Astro’s live collections, defined with defineLiveCollection() in src/live.config.ts, fetch from Directus per request while keeping getLiveEntry() typed. Cache responses at the CDN so Directus doesn’t take every hit.

Directus itself needs a server and database. Self-host it with Docker, or use Directus Cloud. The Astro side can stay on any static host; see deploying to static hosts.

Relational content like listings, menus or service catalogs is where Directus earns its keep. If you’re building a property site, a real estate Astro theme already has listing and detail layouts you can feed from a Directus loader. Reference docs: the Directus SDK guide and Astro’s content loader reference.

FAQ

Is Directus a good CMS for Astro?

Yes, especially for structured or relational content. Directus gives you a SQL database with an admin UI and API, and Astro consumes it through a content loader at build time or a live collection at request time.

Do I need the Directus SDK to use Directus with Astro?

No. Directus has plain REST and GraphQL endpoints, so fetch() works. The SDK adds typed queries, authentication helpers and cleaner filter syntax, which is why it’s the usual choice.

How do I show Directus images in Astro?

Image fields contain a file ID. Build the URL as /assets/<id> on your Directus domain and add transform parameters like width and format. Make sure the file is readable by the Public policy or the images won’t load for visitors.

How do I rebuild Astro when Directus content changes?

Create a Directus Flow with an Event Hook trigger on item create, update and delete, and a Request URL operation that POSTs to your host’s deploy hook. Each change then starts a new build.

Can Directus and Astro run on the same server?

They can, but they’re separate processes. Directus runs as a Node.js service with its database, while Astro is usually built to static files. Hosting the static site on a CDN and Directus on a small server is the common setup.