---
title: Add a blog to your Astro site with a headless CMS API (copy-paste code)
description: Build a blog in Astro that reads posts from a headless CMS API at build time. Complete code for the list page, post pages, rebuilds on publish and draft previews.
url: https://sharpwritecms.com/blog/add-blog-to-astro-with-headless-cms
published: 2026-11-18
updated: 2026-11-19
category: How-to
tags: astro, headless cms, api, blog, javascript
author: The SharpWrite team
site: SharpWrite (https://sharpwritecms.com)
---

# Add a blog to your Astro site with a headless CMS API (copy-paste code)

> **Short answer:** Fetch your posts from the CMS API at build time with a bearer key, generate one page per post with getStaticPaths, and trigger a rebuild with a webhook when you publish. The API key stays on your build machine, so it never reaches visitors, and the finished site is plain static HTML.

Astro is a good fit for a content site: it builds static pages, ships little JavaScript and does not mind where the content comes from. This guide connects it to a headless CMS API and ends with a working blog.

The code uses the SharpWrite content API, but the pattern works for any CMS that returns JSON.

## How it fits together

1. You write and publish a post in the CMS.
2. The CMS sends a webhook to your host, which starts a new build.
3. During the build, Astro fetches all published posts and writes one static HTML page per post.
4. Visitors get fast static pages. The API key is only used during the build.

Because the key is only used at build time, it never appears in the browser.

## Step 1: create the content type

In the CMS, create a content type with the API id `posts` and these fields:

- `title` (short text, required)
- `excerpt` (long text)
- `body` (rich text)
- `tags` (short text)

Write one entry, publish it, then create an API key. Keep it somewhere safe.

## Step 2: set environment variables

Create a `.env` file in your Astro project:

```bash
SHARPWRITE_URL=https://app.sharpwritecms.com
SHARPWRITE_KEY=sw_live_YOUR_KEY
SHARPWRITE_TYPE=posts
```

Add `.env` to `.gitignore`. On your host (Netlify, Vercel, Cloudflare Pages), add the same variables in the project settings.

## Step 3: a small API client

Create `src/lib/sharpwrite.ts`:

```ts
export type Post = {
  id: string;
  slug: string;
  publishedAt: string | null;
  updatedAt: string;
  data: { title?: string; excerpt?: string; body?: string; tags?: string };
};

const base = import.meta.env.SHARPWRITE_URL.replace(/\/$/, "");
const key = import.meta.env.SHARPWRITE_KEY;
const type = import.meta.env.SHARPWRITE_TYPE ?? "posts";

async function get<T>(path: string): Promise<T> {
  const response = await fetch(`${base}${path}`, {
    headers: { Authorization: `Bearer ${key}` },
  });
  if (!response.ok) throw new Error(`CMS answered ${response.status} for ${path}`);
  return (await response.json()) as T;
}

/** Every published post. The API returns up to 100 per request, so follow the pagination. */
export async function getPosts(): Promise<Post[]> {
  const posts: Post[] = [];
  for (let offset = 0; ; offset += 100) {
    const page = await get<{ data: Post[]; pagination: { count: number } }>(
      `/api/public/v1/${type}?limit=100&offset=${offset}`,
    );
    posts.push(...page.data);
    if (page.pagination.count < 100) break;
  }
  return posts;
}
```

The API returns newest first, so the list is already in the right order.

## Step 4: the blog list page

Create `src/pages/blog/index.astro`:

```astro
---
import { getPosts } from "../../lib/sharpwrite";
const posts = await getPosts();
---
<html lang="en">
  <head>
    <title>Blog</title>
    <meta name="description" content="Notes and updates." />
  </head>
  <body>
    <h1>Blog</h1>
    <ul>
      {posts.map((post) => (
        <li>
          <a href={`/blog/${post.slug}`}>{post.data.title}</a>
          <p>{post.data.excerpt}</p>
        </li>
      ))}
    </ul>
  </body>
</html>
```

## Step 5: one page per post

Create `src/pages/blog/[slug].astro`:

```astro
---
import { getPosts } from "../../lib/sharpwrite";

export async function getStaticPaths() {
  const posts = await getPosts();
  return posts.map((post) => ({ params: { slug: post.slug }, props: { post } }));
}

const { post } = Astro.props;
---
<html lang="en">
  <head>
    <title>{post.data.title}</title>
    <meta name="description" content={post.data.excerpt} />
    <link rel="canonical" href={new URL(`/blog/${post.slug}`, Astro.site)} />
  </head>
  <body>
    <article>
      <h1>{post.data.title}</h1>
      <div set:html={post.data.body} />
    </article>
  </body>
</html>
```

Rich text arrives as sanitized HTML, so `set:html` is the right way to render it. Images inside the body use full URLs, so they work on your own domain.

Set `site` in `astro.config.mjs` so the canonical link works:

```js
import { defineConfig } from "astro/config";
export default defineConfig({ site: "https://yoursite.com" });
```

## Step 6: rebuild when you publish

A static site only updates when it is rebuilt. Add a webhook in the CMS that points at your host's deploy hook URL (Netlify, Vercel and Cloudflare Pages all offer one). The CMS sends a request when an entry is published, updated, unpublished or deleted, and your host rebuilds the site.

Deploy hooks do not need signature checking. If you build your own endpoint instead, verify the `X-SharpWrite-Signature` header, which is an HMAC-SHA256 of the timestamp and body, before you trust the request.

## Step 7: preview drafts without publishing

To see drafts, create a preview token in the CMS and send it next to your API key:

```ts
headers: {
  Authorization: `Bearer ${key}`,
  "X-Preview-Token": previewToken,
}
```

Use it only in a private preview build. A preview token must never end up in a page visitors can read.

## Common problems

- **401 from the API.** The key is missing, wrong or revoked. Check that the environment variable is set on the build machine.
- **A new post does not show up.** The build did not run. Check that the webhook fired and that the host started a deploy.
- **The list stops at 100.** You did not follow pagination. Use the loop in `getPosts`.
- **Rate limit (429).** Each key allows 120 requests a minute. A normal build makes a handful, but a loop that fetches every post one by one can hit it. Fetch the list once and reuse it.

## Make the blog rank

A few small additions help search and AI answers:

- Give every post a unique title and meta description.
- Add the canonical link, as above.
- Add JSON-LD `BlogPosting` data to each post page.
- Generate a sitemap with `@astrojs/sitemap`.

For more on structuring pages so assistants can quote them, see [what an AI-native CMS is](https://sharpwritecms.com/blog/what-is-an-ai-native-cms). Ready to try it with real content? [Start a 7-day free trial](https://app.sharpwritecms.com/sign-in).

## Frequently asked questions

### Can Astro use a headless CMS?

Yes. Astro can fetch content from any API at build time, then generate static pages with `getStaticPaths`. A headless CMS that returns JSON works well, and the API key stays on your build machine.

### How do I fetch CMS content in Astro?

Use `fetch` inside the frontmatter of an `.astro` file or in a helper module, send your API key in an `Authorization: Bearer` header, and map the response to your markup. For dynamic routes, return the posts from `getStaticPaths`.

### Is it safe to put the CMS API key in Astro?

Yes, as long as the request runs at build time or on the server. Keep the key in an environment variable and never use it in browser code. Anything in client-side JavaScript is visible to every visitor.

### How do I rebuild my Astro site when I publish?

Add a webhook in the CMS that calls your host's deploy hook. The host then runs a new build, which fetches the latest content and rewrites the static pages.

### Does SharpWrite work with frameworks other than Astro?

Yes. The API is plain JSON over HTTP, so Next.js, SvelteKit, Nuxt, Eleventy and static sites can all read the same content with a normal `fetch` call.

---

## Try SharpWrite

SharpWrite is an AI-native CMS for one-person businesses. A clean editor, a plain REST API and built-in AI.

- [Start a 7-day free trial](https://app.sharpwritecms.com/sign-in)
- [See pricing](https://sharpwritecms.com/pricing): Cloud from $39 a month, or a one-time self-host license from $149
- [Read this post on the web](https://sharpwritecms.com/blog/add-blog-to-astro-with-headless-cms)
