Back to the blog

Astro with headless WordPress: setup, publishing and trade-offs

Connect Astro to WordPress through its REST API: TypeScript, routes, publishing, security, SEO and headless architecture maintenance.

Published
Reading time
15 minutes
Topics
Astro · WordPress · Headless CMS · TypeScript · Web security

Yes, Astro can use WordPress as its CMS. Editors keep WordPress for managing content, while Astro builds the public website from the WordPress REST API. You keep the dashboard, but not the WordPress theme or frontend: Astro becomes responsible for routes, design, SEO and delivery.

This separation can reduce the attack surface of the public website when Astro outputs static files, but it does not make WordPress invulnerable. The dashboard, API, plugins and hosting still need protection, and a compromised CMS can feed malicious content into the next build.

The API request is the easy part. The important decisions are what happens after an editor clicks Publish, how drafts are previewed, where metadata comes from and who maintains both systems.

This guide presents a reproducible architecture and code example based on the official documentation. It is not a client case or a claim that I have deployed this stack in production. Its purpose is to show what I would resolve before recommending it for a real project.

What headless WordPress means in an Astro project

In a conventional WordPress installation, the CMS stores the content and generates the website people visit. Its theme, templates and many plugins participate in that frontend.

A headless architecture separates those responsibilities:

WordPress Astro
Editing dashboard, users and permissions Public routes and templates
Posts, pages, categories and media Components, styling and responsive behaviour
Draft and publication states Titles, canonicals, schema and sitemap
Content API Build, deployment and frontend performance

Astro fetches the data and decides how to turn it into pages. WordPress no longer controls the public presentation.

This distinction prevents a common misunderstanding: connecting the systems does not convert a WordPress theme into Astro components. It does not automatically transfer Elementor layouts, shortcodes, forms or plugin blocks either. You receive the data exposed by the API and build everything else.

If you are still choosing a platform, read the Astro versus WordPress comparison. This guide starts from a more specific requirement: the team wants to retain the WordPress dashboard while developing the frontend in Astro.

When Astro and WordPress make sense together

I would consider this architecture when several conditions apply:

  • An existing WordPress site contains substantial content worth retaining.
  • Editors know its dashboard and need to keep using it.
  • The frontend needs a design or architecture controlled in code.
  • Someone owns WordPress, Astro and the connection between them.
  • The budget covers previews, deployments and maintenance, not only the first API request.

I would not add it as a just-in-case dashboard. If one technical person publishes occasional content, Markdown or MDX may be simpler. For a new project, it is also worth comparing a CMS designed for headless delivery, as discussed in Astro with Sanity as a WordPress alternative.

Nor does headless remove WordPress. The installation still needs hosting, backups, updates, permissions and plugin oversight. You have decoupled the frontend, not the responsibility for the CMS.

Fetching WordPress content from Astro

WordPress provides a REST API at /wp-json/wp/v2/. Public content such as published posts generally requires no authentication.

Astro’s official WordPress guide also covers GraphQL through plugins such as WPGraphQL. This example uses REST because it is built into WordPress and demonstrates the integration without another dependency; GraphQL may suit projects that need more specific queries and can take responsibility for that plugin.

For example, this endpoint returns posts:

https://cms.example.com/wp-json/wp/v2/posts

Open the endpoint and inspect the real response before writing components. Pages use /pages, media use /media, and a custom post type is only available if it was registered with show_in_rest: true.

A small typed function can fetch all posts:

import { z } from 'astro/zod';

const WORDPRESS_URL = import.meta.env.WORDPRESS_URL;

const WordPressPostSchema = z.object({
  id: z.number().int(),
  slug: z.string().min(1),
  date: z.string(),
  modified: z.string(),
  title: z.object({ rendered: z.string() }),
  content: z.object({ rendered: z.string() }),
});

const WordPressPostsSchema = z.array(WordPressPostSchema);

export type WordPressPost = z.infer<typeof WordPressPostSchema>;

export async function getWordPressPosts(): Promise<WordPressPost[]> {
  const posts: WordPressPost[] = [];
  let page = 1;

  while (true) {
    const url = new URL('/wp-json/wp/v2/posts', WORDPRESS_URL);
    url.searchParams.set('page', String(page));
    url.searchParams.set('per_page', '100');
    url.searchParams.set(
      '_fields',
      'id,slug,date,modified,title,content',
    );

    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`WordPress API returned ${response.status}`);
    }

    const pagePosts = WordPressPostsSchema.parse(await response.json());
    posts.push(...pagePosts);

    const totalPages = Number(
      response.headers.get('X-WP-TotalPages') ?? 1,
    );

    if (page >= totalPages) return posts;
    page += 1;
  }
}

WORDPRESS_URL is the CMS origin, such as https://cms.example.com. The example limits the payload through _fields. WordPress paginates collections and exposes the total page count through X-WP-TotalPages; a single request would omit content once the collection exceeds the configured limit. The pagination documentation sets a maximum of 100 records per request.

Authors, featured media and terms require additional requests or _embed. Measure the response size and avoid embedding relationships the page never uses. WordPress documents _fields and _embed as global parameters.

Generating Astro routes for WordPress posts

For a statically generated website, getStaticPaths() can turn each WordPress slug into an Astro URL:

---
import sanitizeHtml from 'sanitize-html';
import {
  getWordPressPosts,
  type WordPressPost,
} from '../../lib/wordpress';

export async function getStaticPaths() {
  const posts = await getWordPressPosts();

  return posts.map((post) => ({
    params: { slug: post.slug },
    props: { post },
  }));
}

const { post } = Astro.props as { post: WordPressPost };

const title = sanitizeHtml(post.title.rendered, {
  allowedTags: [],
  allowedAttributes: {},
});

const content = sanitizeHtml(post.content.rendered, {
  allowedTags: [
    'p', 'h2', 'h3', 'h4', 'ul', 'ol', 'li', 'a',
    'strong', 'em', 'blockquote', 'figure', 'figcaption',
    'img', 'pre', 'code',
  ],
  allowedAttributes: {
    a: ['href', 'title'],
    img: ['src', 'alt', 'width', 'height', 'loading'],
  },
  allowedSchemes: ['https', 'mailto'],
  allowProtocolRelative: false,
});
---

<article>
  <h1>{title}</h1>
  <div set:html={content} />
</article>

This is a starting point, not a production-ready component. The example uses sanitize-html as a server-build option; it would need to be installed, kept current and tested against the chosen configuration. Astro’s set:html directive injects HTML without escaping it, so the content is sanitised against an allowlist first. Adapt that list to the blocks the project actually supports. Do not broadly enable iframe, style, event attributes or classes merely to recover broken styling.

You also need styles for the HTML Gutenberg produces. Alignment classes, tables, galleries, captions and embeds do not automatically inherit the Astro design. Content that looks correct in the editor can break on the public website unless every supported block is tested.

Publishing in WordPress does not update a static site by itself

Astro prerenders pages by default. When it fetches posts during the build, the deployed website contains a snapshot of that data. A later WordPress update will not appear until another build is completed and deployed.

A complete workflow usually looks like this:

  1. An editor publishes or updates a WordPress post.
  2. WordPress sends a webhook to the deployment service.
  3. The provider starts the Astro build.
  4. Astro fetches the API and generates the new pages.
  5. Publication finishes when the deployment is live, not when WordPress saves the post.

Editors need to understand that delay, and the webhook should be protected. You also need a policy for WordPress API failures during a build: failing and retaining the previous deployment is usually safer than publishing an incomplete website.

The alternative is Astro’s on-demand rendering. It can fetch WordPress on each request or behind a cache, but it requires an adapter and runtime. More immediate content comes with server availability, latency, caching and operating costs. The choice is a trade-off between freshness, simplicity and dependence on the CMS.

Drafts and previews need a separate workflow

The public API returns published content. Drafts, revisions and protected fields require authentication and a preview route that search engines cannot index.

WordPress supports Application Passwords over HTTPS for remote access. Credentials belong on the server or in the build environment, never in browser code.

A complete preview workflow needs to answer at least these questions:

  • Who can open the preview, and for how long?
  • How is the requested draft or revision identified?
  • Which Astro template renders it?
  • How is the preview URL kept out of search indexes?
  • Which blocks and fields behave exactly as they do in production?

If nobody needs previews, you can avoid some of this work. If an editorial team considers them essential, they should be part of the architecture and estimate from the beginning.

How to secure Astro with headless WordPress

No configuration can guarantee that this architecture will never be vulnerable. A realistic goal is to remove unnecessary entry points, contain the impact of a compromised account or plugin and detect failures before they reach the public website.

A static Astro frontend avoids executing WordPress PHP and plugins for every visitor, but WordPress remains connected to the internet. The build also trusts its API. If an attacker compromises the CMS and gains permission to publish malicious HTML, Astro can turn that payload into a perfectly valid static page.

Risk Primary control
Outdated WordPress core or plugin Updates, fewer plugins and restorable backups.
Compromised editorial account Least-privilege roles, strong passwords and a second factor.
Leaked API credential Server-side secret, dedicated user and rotation.
Malicious HTML in content.rendered Runtime data validation and allowlist-based sanitisation.
Forged deployment webhook Verifiable signature or secret, HTTPS and rate limits.
Preview discovered by a third party Authentication, authorisation and expiry; noindex is not access control.
WordPress outage or oversized response Timeouts, size limits, caching and the last known good deployment.

WordPress remains an application that needs protection

A headless installation needs the same care as any other internet-facing WordPress site. The official WordPress hardening guide recommends keeping core and plugins current, using software from trusted sources, restricting permissions, disabling dashboard file editing when it is not needed and maintaining backups that can actually be restored.

I would also apply these decisions:

  • Put the CMS on an origin such as cms.example.com to define cookies, headers and ownership more clearly. A subdomain is not a security control by itself.
  • Remove plugins and themes that add nothing to the headless CMS. Every extension adds code that must be updated and reviewed.
  • Give each person the least privileged role they need. An author should not be able to install plugins or edit PHP.
  • Protect accounts with a second factor and reserve administrator accounts for administrative work.
  • Keep the dashboard, API and webhooks on HTTPS. Hiding the login URL may reduce automated noise, but it does not replace these controls.

A readable public API is not automatically a vulnerability either. Published posts are already public. What matters is that drafts, private fields and write operations still require authentication and authorisation, and that responses do not expose data the frontend does not need.

Credentials belong on the server only

I would send no credentials when reading public posts. Previews and protected operations should use a separate, revocable Application Password attached to a dedicated user with the minimum capabilities. Do not reuse an administrator’s primary password.

The secret belongs in the build or server environment. Astro distinguishes public variables from server secrets and documents that a secret client variable cannot be safe. Therefore:

  • Do not expose the password through a public environment variable or client module.
  • Do not make authenticated requests from a component shipped to the browser.
  • Do not write credentials, Authorization headers or secret deployment URLs to logs.
  • Revoke and replace a credential when it is exposed or no longer needed.

An obscure URL and a noindex tag do not secure a preview. The route needs to verify a session or signed token, authorise access to the requested content and expire that access. noindex addresses search engines; it does not stop another person from opening the page.

TypeScript does not validate the API, and set:html does not sanitise content

A TypeScript interface describes the value you expect, but it disappears at runtime. That is why the earlier example parses the response through a Zod schema. A production implementation should also set response-size limits, timeouts and explicit error handling.

The second trust boundary is the HTML returned by WordPress. OWASP recommends HTML sanitisation when authored formatting must be retained, rather than injecting the value directly. The example uses a small allowlist of tags and attributes. If a Gutenberg block needs a class, iframe or additional attribute, review and add that exact requirement instead of broadly enabling arbitrary HTML.

Sanitise before set:html, during the build or on the server. Keep the sanitiser patched, and avoid mutating the cleaned string in ways that make it unsafe again. Content written by administrators still benefits from this defence because an account or plugin can be compromised.

Protect the webhook and contain failures

An endpoint that starts deployments must not accept arbitrary requests. Treat a provider’s secret deployment URL as a credential and rotate it if it leaks. For a custom integration, the OWASP Webhook Security Cheat Sheet recommends HTTPS, verifiable signatures such as HMAC, replay or retry protection, payload and rate limits, and logs without secrets.

With static generation, a WordPress failure should abort the build and retain the previous deployment. With on-demand rendering, WordPress becomes part of every public request: validation and sanitisation must be joined by timeouts, caching, response limits and an outage strategy.

Finally, configure security headers on the Astro frontend. A CSP can restrict scripts, connections, images and frames, but OWASP treats it as defence in depth rather than the primary XSS control. img-src needs to allow the WordPress media origin; connect-src only needs the API if the browser calls it directly. My guide to security headers for a website explains that configuration and its limits.

Before launch, I would check at least these points:

  1. WordPress updates, roles, second factor, file permissions and backup restoration.
  2. Only the required endpoints and fields, with no credential for public content.
  3. Preview and deployment secrets kept out of the client, repository and logs.
  4. Runtime response validation and HTML sanitisation before rendering.
  5. Authenticated, rate-limited webhooks tested with invalid signatures and retries.
  6. Preview routes protected by real authorisation and expiry.
  7. Headers and CSP verified against the deployed Astro response.
  8. Monitoring for access anomalies, failed builds, unexpected changes and pending updates.

Who owns SEO in a headless architecture

Astro is the public website, so it must output the title, description, canonical, Open Graph metadata, schema, sitemap and hreflang links. Installing an SEO plugin in WordPress does not automatically configure the <head> of a decoupled frontend.

You can expose SEO fields through the API and map them in Astro, but choose one source of truth. Duplicating titles in WordPress and the repository without an ownership rule creates inconsistencies.

Each piece of content also needs one public version. If the same post is accessible through WordPress and Astro, two URLs contain identical or very similar information. The usual approach is to stop the WordPress frontend from competing with Astro and output consistent canonicals. Google describes redirects and rel="canonical" as strong signals for consolidating duplicate URLs.

When Astro replaces existing WordPress URLs, prepare a one-to-one mapping, permanent redirects and a new sitemap. Google’s site migration guidance recommends testing the mapping, updating canonicals and keeping redirects in place long enough. The WordPress to Astro migration guide covers that work without mixing it into the headless connection itself.

The maintenance this architecture adds

Astro and WordPress can solve a genuine requirement together, but the pair is not simpler than either system on its own. You need to maintain:

  • WordPress, PHP, its database, users and plugins.
  • The Astro project, dependencies and deployment.
  • The contract between the API and TypeScript types.
  • Webhooks, environment variables and credentials.
  • Supported blocks, previews, images and metadata.
  • Alerts for failed builds and stale content.

A field, plugin or response change can break the frontend while WordPress itself still works. The project scope therefore needs tests with real content and a named owner after launch. Fixes, updates and improvements also need to be separated in the maintenance agreement.

How I would make the decision

I would use headless WordPress with Astro when retaining the dashboard is a proven requirement and frontend control justifies the integration. I would not choose it simply because the combination is technically possible.

This portfolio uses content collections and MDX because I am the editor, I version content with the code and I do not need a separate dashboard. A project with a WordPress-trained editorial team could justify a different decision.

The final question is not “can they be connected?”. It is this:

Which workflow lets the responsible person publish, preview and maintain content without adding more complexity than the project can support?

If you are planning a professional website and an editing dashboard is a requirement, decide that before fixing the architecture and budget. My web design and development service explains the base scope and maintenance approach; a CMS integration would be estimated around the content, editors and publishing workflow involved.