Skip to content
SharpWrite
Docs menu

Connect your site

SharpWrite does not render your website; your website reads SharpWrite. This page shows the usual patterns: fetching content, rebuilding when you publish and previewing drafts.

Keep the address and key in environment variables

Use two variables in every example below. The API key belongs on your server or in your build, never in code that runs in a visitor's browser.

.env
SHARPWRITE_URL=https://app.sharpwritecms.com   # or the address of your Self-host install
SHARPWRITE_KEY=sw_live_YOUR_KEY

Create the key under MCP in the app. The full list of endpoints is in the API reference.

Astro

For a static blog, fetch the list in getStaticPaths and the entry on each page. Astro runs this at build time, so the key never reaches the browser.

src/pages/blog/[slug].astro
---
export async function getStaticPaths() {
  const res = await fetch(`${import.meta.env.SHARPWRITE_URL}/api/public/v1/posts?limit=100`, {
    headers: { Authorization: `Bearer ${import.meta.env.SHARPWRITE_KEY}` },
  });
  if (!res.ok) throw new Error(`SharpWrite answered ${res.status}`);
  const { data } = await res.json();
  return data.map((post) => ({ params: { slug: post.slug }, props: { post } }));
}
const { post } = Astro.props;
---
<h1>{post.data.title}</h1>
<article set:html={post.data.body} />

A complete, ready-to-run blog is in the examples/astro-blog folder of the SharpWrite repository, including a preview mode and clear error messages when the key or address is wrong.

Next.js

In the App Router, fetch from a Server Component. Use revalidate so the page is cached and refreshed on a schedule, or call revalidatePath from a webhook handler for instant updates.

app/blog/[slug]/page.tsx
import { notFound } from "next/navigation";

async function getPost(slug: string) {
  const res = await fetch(`${process.env.SHARPWRITE_URL}/api/public/v1/posts/${slug}`, {
    headers: { Authorization: `Bearer ${process.env.SHARPWRITE_KEY}` },
    next: { revalidate: 60 },
  });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`SharpWrite answered ${res.status}`);
  return (await res.json()).data;
}

export default async function Post({ params }: { params: Promise<{ slug: string }> }) {
  const post = await getPost((await params).slug);
  if (!post) notFound();
  return (
    <article>
      <h1>{post.data.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.data.body }} />
    </article>
  );
}

Rich text arrives as sanitised HTML, so rendering it with dangerouslySetInnerHTML is expected. Do not render fields you did not mark as rich text this way.

Any other server or language

It is a plain HTTPS JSON API. Anything that can send a header can read it.

Node.js (no framework)
const res = await fetch(`${process.env.SHARPWRITE_URL}/api/public/v1/posts?limit=10`, {
  headers: { Authorization: `Bearer ${process.env.SHARPWRITE_KEY}` },
});
const { data, pagination } = await res.json();
Python
import os, requests

res = requests.get(
    f"{os.environ['SHARPWRITE_URL']}/api/public/v1/posts",
    headers={"Authorization": f"Bearer {os.environ['SHARPWRITE_KEY']}"},
    params={"limit": 10},
    timeout=10,
)
res.raise_for_status()
posts = res.json()["data"]

Reading more than one page of entries

A list returns up to 100 entries. Keep requesting with a larger offset until you get fewer entries than your limit.

async function allPosts() {
  const limit = 100;
  const posts = [];
  for (let offset = 0; ; offset += limit) {
    const res = await fetch(`${process.env.SHARPWRITE_URL}/api/public/v1/posts?limit=${limit}&offset=${offset}`, {
      headers: { Authorization: `Bearer ${process.env.SHARPWRITE_KEY}` },
    });
    const { data } = await res.json();
    posts.push(...data);
    if (data.length < limit) return posts;
  }
}

Each key can make 120 requests a minute, so fetch lists at build time or cache them rather than calling the API on every visit.

Rebuild your site when content changes

A static site shows new content only after it is rebuilt. Create a deploy hook at your host (Vercel, Netlify and Cloudflare Pages all offer one; it is just a URL), then add it under Webhooks in SharpWrite. SharpWrite calls it when an entry is published, changed, unpublished or deleted. A deploy hook does not need the signature check.

If you handle the webhook yourself, for example to refresh one page instead of the whole site, verify the signature first. The code is in the API reference.

Preview drafts before publishing

Create a draft preview token in the app and keep it on your server. A private route on your site sends it next to the API key and gets drafts as well as published entries.

Server-side preview request
const res = await fetch(`${process.env.SHARPWRITE_URL}/api/public/v1/posts/${slug}`, {
  headers: {
    Authorization: `Bearer ${process.env.SHARPWRITE_KEY}`,
    "X-Preview-Token": process.env.SHARPWRITE_PREVIEW_TOKEN,
  },
  cache: "no-store",
});
  • Each entry in a preview response has a status of draft or published, so you can show a "Draft" banner.
  • Put the preview route behind a login or a secret address. Anyone who can open it can read your drafts.
  • Preview responses are never cached. Do not cache them yourself either.

Images

Images you add in the editor arrive inside the rich-text HTML with full addresses, so they load on your own domain with no extra work. Uploaded media has a public address, so do not upload anything you would not want a visitor to be able to open.