Documentation
Connect a website to sitecms: the integration guide
By Oskar ÖstlindUpdated Published
Short answer
Run the init command for your framework in the project root (for example npx sitecms-next init), paste in the API key from the panel, declare editable fields in sitecms.config.ts and read them on the server with getContent(). There are packages for Next.js, Astro, Nuxt, SvelteKit and plain JavaScript. The only environment variable is CMS_API_KEY. Saving in the panel (or publishing, if the site has draft mode) refreshes the site within seconds.
Which package do I install?
There is one npm package per framework, and all of them are built on the framework-neutral core sitecms-js. Each is set up with one command, run in the project root where package.json is. The sections below start with Next.js and then cover the other four.
| Package | Version | Requirements | Set up with |
|---|---|---|---|
sitecms-next | 0.7.1 | Next.js 14.2 or later with the App Router. Node 18.17 or later | npx sitecms-next init |
sitecms-astro | 0.1.1 | Astro 5 or later. Node 18.17.1 or later | npx sitecms-astro init |
sitecms-nuxt | 0.1.1 | Nuxt 4. Node 20.19 or later | npx sitecms-nuxt init |
sitecms-sveltekit | 0.1.1 | SvelteKit 2 or 3 with Svelte 5. Node 18.17 or later | npx sitecms-sveltekit init |
sitecms-js | 0.1.1 | No framework needed. Node 18.17 or later | npx sitecms-js init |
How do I install sitecms-next (Next.js)?
Create an account and a site in the panel (the panel is in Swedish), copy the API key, and run this in the project root, where package.json is:
npx sitecms-next initThe command checks the key against sitecms before it writes anything, saves CMS_API_KEY in .env.local (and makes sure .gitignore covers it), installs sitecms-next if it is missing, creates the routes and the config file, and adds "prebuild": "sitecms-next sync" to package.json. It can be run again: existing routes and config are never overwritten. app/layout.tsx and next.config are never touched.
Which environment variables do I need?
Only CMS_API_KEY. It decides which site the content is read from and verifies the webhook. Put it in .env.local and in the environment of your host (Vercel, Netlify, Cloudflare, Render or your own server). Nuxt reads .env instead of .env.local. CMS_API_URL is optional and defaults to https://sitecms.se.
How do I declare the editable fields?
List the pages and fields the customer may edit in sitecms.config.ts. Field types for pages are text, richtext (Markdown, also delivered as HTML) and image (URL plus alt text). Custom content types have more field types, described below. Give each field a label, a help text and a default with today's content.
import { defineConfig } from "sitecms-next";
// Vilka sidor och fält kunden ska kunna redigera. Synkas till sitecms med
// "sitecms-next sync" (prebuild). Kundens innehåll skrivs aldrig över;
// nya fält får sitt default-värde.
export default defineConfig({
pages: [
{
slug: "home",
title: "Startsida",
description: "Det besökaren ser först.",
blocks: [
{ key: "hero.title", label: "Rubrik", help: "Max 60 tecken", default: "Välkommen" },
{
key: "hero.image",
type: "image",
label: "Hero-bild",
default: "https://exempel.se/hero.jpg",
defaultAlt: "Byggarbetare på ett tak",
},
{ key: "intro.body", type: "richtext", label: "Ingress" },
],
},
],
});
{
"scripts": {
"prebuild": "sitecms-next sync"
}
}The sync runs before each build. It creates missing pages and fields in sitecms and never overwrites what the customer has written. Fields removed from the config stay until you run sitecms-next sync --prune. An invalid config stops the build.
How do I read content in a page?
// app/page.tsx — en serverkomponent
import Image from "next/image";
import { block, getContent, image, text } from "sitecms-next";
export default async function Home() {
const content = await getContent();
const hero = image(content, "home", "hero.image");
return (
<main>
<h1>{text(content, "home", "hero.title", "Välkommen")}</h1>
{hero ? <Image src={hero.src} alt={hero.alt} width={1200} height={630} /> : null}
<div dangerouslySetInnerHTML={{ __html: block(content, "home", "intro.body").html }} />
</main>
);
}getContent()returns the whole site:{ site, pages, services, seo }.text(content, page, key, fallback?)returns a string.image(content, page, key)returns{ src, alt }ornull.block(content, page, key)returns{ value, html, alt }, always strings.htmlis ready-made HTML for rich text and escaped text otherwise.seo(content, page)returns{ title, description, ogImage }ornull.
How do I use SEO fields and posts?
The customer edits SEO title and description per page in the panel. Read them in generateMetadata:
// app/page.tsx
import type { Metadata } from "next";
import { getContent, seo } from "sitecms-next";
export async function generateMetadata(): Promise<Metadata> {
const meta = seo(await getContent(), "home");
return {
title: meta?.title ?? undefined,
description: meta?.description ?? undefined,
openGraph: meta?.ogImage ? { images: [meta.ogImage] } : undefined,
};
}Posts (news) use getPosts() for the published list, newest first and without body text, and getPost(slug) for one post with body (Markdown) and bodyHtml. It returns null when the post is missing or not published.
// app/nyheter/[slug]/page.tsx
import { notFound } from "next/navigation";
import { getPost } from "sitecms-next";
export default async function Post({ params }: { params: Promise<{ slug: string }> }) {
const post = await getPost((await params).slug);
if (!post) notFound();
return (
<article>
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.bodyHtml }} />
</article>
);
}How does revalidation work without a new deploy?
Every request made by sitecms-next is tagged with the cache tag sitecms. When the customer saves (or publishes, if the site has draft mode), sitecms sends a signed POST to your revalidate route (/api/sitecms/revalidate), which clears the tag. The next visitor gets the new content. init creates the route for you:
export { POST } from "sitecms-next/revalidate";- The webhook is signed with HMAC-SHA256 and a timestamp. The package verifies it and rejects anything older than 300 seconds.
- On the first production build,
sitecms-next syncsends the site's address so sitecms can fill in the revalidate URL, but only if it is empty. Preview deployments never set it. - Check the connection at any time with
npx sitecms-next check, or with the test button under Integration in the panel. - A site that is fully static (
output: "export") cannot revalidate on the server. Use a deploy hook as the revalidate URL instead.
How do I set up live preview?
When the customer edits a page in the panel, the real site is shown in an iframe beside the fields and updates as they type, before anything is saved. Clicking a marked element jumps to its field. It needs sitecms-next 0.4 or later. Unsaved changes live in a short-lived session and are visible only in the preview. If the site has draft mode, the preview also shows saved drafts, so the customer can check a change before publishing it.
First the route app/api/sitecms/preview/route.ts, which init creates for you:
export { GET } from "sitecms-next/preview";Add the component last in <body>:
// app/layout.tsx
import { SitecmsPreview } from "sitecms-next/preview";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="sv">
<body>
{children}
{/* Renderar ingenting utanför förhandsgranskningen. */}
<SitecmsPreview />
</body>
</html>
);
}Mark editable elements with editable(page, key), using the same page and key as in the config:
// app/page.tsx
import Image from "next/image";
import { block, editable, getContent, image, text } from "sitecms-next";
export default async function Home() {
const content = await getContent();
const hero = image(content, "home", "hero.image");
return (
<main>
{/* data-sitecms="home:hero.title" — klickbar i förhandsgranskningen */}
<h1 {...editable("home", "hero.title")}>{text(content, "home", "hero.title", "Välkommen")}</h1>
{hero ? (
<Image {...editable("home", "hero.image")} src={hero.src} alt={hero.alt} width={1200} height={630} />
) : null}
<div
{...editable("home", "intro.body")}
dangerouslySetInnerHTML={{ __html: block(content, "home", "intro.body").html }}
/>
</main>
);
}Allow the panel to embed the site, and remove X-Frame-Options if the site sets it:
// next.config.ts
import type { NextConfig } from "next";
import { previewFrameHeaders } from "sitecms-next/preview";
const nextConfig: NextConfig = {
async headers() {
return [
{
source: "/:path*",
// Content-Security-Policy: frame-ancestors 'self' https://sitecms.se https://www.sitecms.se
// Ta bort X-Frame-Options om sajten sätter den — CSP:n ersätter den.
headers: previewFrameHeaders(),
},
];
},
};
export default nextConfig;How do I add cookie-free analytics?
sitecms-next 0.6 and later has built-in visitor statistics, shown in the panel under SEO & Trafik (SEO & Traffic): visitors, page views, pages, sources, countries and devices. It uses no cookies and no local storage and loads no third-party script. sitecms stores daily totals only, never the IP address, user agent or raw events, and unique visitors are counted with a daily hash so nobody can be followed between days.
export { POST } from "sitecms-next/analytics";// app/layout.tsx
import { SitecmsAnalytics } from "sitecms-next/analytics";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="sv">
<body>
{children}
{/* Renderar ingenting i förhandsgranskningen. Inga cookies. */}
<SitecmsAnalytics />
</body>
</html>
);
}To debug, the network tab should show a POST /api/sitecms/events returning 204 on each navigation. A 404 means the route is missing. A 204 with nothing in the panel usually means CMS_API_KEY is missing at the host or belongs to another site.
How do I send quote requests to the panel?
A contact or quote form on the site can send its submissions to the panel with submitQuoteRequest(), and attachments (jpg, png, webp, heic or pdf, up to 10 MB each, at most 10) with uploadQuoteAttachment(). Do it in a server action, never from the browser. Phone number and consent are required, and the API rate-limits per IP hash. Requests are deleted after 12 months, and the panel can email the site's contact address.
// app/offert/actions.ts
"use server";
import { headers } from "next/headers";
import { SitecmsError, hashIp, submitQuoteRequest, uploadQuoteAttachment } from "sitecms-next";
export type OffertResultat =
| { ok: true; id: string }
| { ok: false; fel: string; falt?: Record<string, string> };
export async function skickaOffert(formData: FormData): Promise<OffertResultat> {
// 1. Honeypot: fältet är dolt för människor — ifyllt betyder bot. Låtsas lyckas.
if (formData.get("webbplats")) return { ok: true, id: "" };
// 2. Tidsfälla: formuläret renderades med started=Date.now(); under 3 s är en bot.
const started = Number(formData.get("started") ?? 0);
if (!started || Date.now() - started < 3_000) return { ok: true, id: "" };
// 3. ipHash: saltad hash av IP:n, så att sitecms kan rate-limita utan att se adressen.
const h = await headers();
const ip = h.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "";
const ipHash = await hashIp(ip, process.env.CMS_IP_SALT!);
try {
// 4. Bilagor först (jpg/png/webp/heic/pdf, max 10 MB per fil, max 10 st) …
const filer = formData.getAll("bilder").filter((f): f is File => f instanceof File && f.size > 0);
const attachments = await Promise.all(filer.map((f) => uploadQuoteAttachment(f, f.name, { ipHash })));
// 5. … sedan själva förfrågan.
const { id } = await submitQuoteRequest({
name: String(formData.get("namn") ?? ""),
phone: String(formData.get("telefon") ?? ""),
email: String(formData.get("epost") ?? ""),
jobType: String(formData.get("typ") ?? ""),
description: String(formData.get("beskrivning") ?? ""),
consent: formData.get("samtycke") === "on",
customerType: (formData.get("kundtyp") as "privat" | "foretag" | null) || null,
budget: String(formData.get("budget") ?? "") || null,
rot: formData.get("rot") === "on",
postalCode: String(formData.get("postnummer") ?? "") || null,
desiredStart: String(formData.get("start") ?? "") || null,
source: String(formData.get("kalla") ?? "") || null, // referrer/utm från klienten
attachments,
extra: { takyta: String(formData.get("takyta") ?? "") }, // egna fält, visas som tabell i panelen
ipHash,
});
return { ok: true, id };
} catch (err) {
if (err instanceof SitecmsError && err.status === 400) {
// Fältfel på svenska: { phone: "Ange ett svenskt telefonnummer…", … } — mappa till formulärets namn.
const namn: Record<string, string> = { name: "namn", phone: "telefon", email: "epost", jobType: "typ", description: "beskrivning", consent: "samtycke", postalCode: "postnummer", customerType: "kundtyp", desiredStart: "start" };
const falt = Object.fromEntries(Object.entries(err.fields).map(([k, v]) => [namn[k] ?? k, v]));
return { ok: false, fel: "Kontrollera fälten nedan.", falt };
}
if (err instanceof SitecmsError && (err.status === 429 || err.status === 413)) {
return { ok: false, fel: err.message }; // serverns svenska meddelande
}
console.error("offert:", err);
return { ok: false, fel: "Något gick fel. Försök igen eller ring oss." };
}
}How do I connect an Astro site?
sitecms-astro needs Astro 5 or later. Run the init command in the project root. It checks the key, saves CMS_API_KEY in .env.local, installs the package, adds sitecms() to integrations in astro.config, creates sitecms.config.ts and adds "prebuild": "sitecms-astro sync" to package.json. The routes for revalidation, preview and analytics are added by the integration, not written into your project.
npx sitecms-astro init---
import { getContent, text, editable } from "sitecms-astro";
// { request: Astro } lets the page show unsaved changes in the panel's live preview.
const content = await getContent({ request: Astro });
---
<h1 {...editable("home", "hero.title")}>{text(content, "home", "hero.title", "Welcome")}</h1>Call it in the frontmatter, in an endpoint or in middleware, never in a client script. Astro builds statically by default, and most of sitecms works then, but three things need pages or routes that render on request, which means an adapter: live preview, visitor statistics and an instant refresh when the customer saves. On a fully static site without an adapter, paste a deploy hook URL from your host as the revalidate URL under Integration, and the site is rebuilt each time the customer saves or publishes.
How do I connect a Nuxt site?
sitecms-nuxt needs Nuxt 4 and Node 20.19 or later (on Node 22, 22.12 or later). Nuxt 3 is not supported. The init command saves CMS_API_KEY in .env (Nuxt reads .env, not .env.local), adds the module to modules in nuxt.config.ts, creates sitecms.config.ts and adds prebuild and pregenerate scripts that run the sync. The module adds the revalidate, events and preview routes itself.
npx sitecms-nuxt init<script setup lang="ts">
import { text } from "sitecms-nuxt/helpers";
const { data: content } = await useSitecmsContent();
</script>
<template>
<h1 v-if="content" v-bind="editable('home', 'hero.title')">{{ text(content, "home", "hero.title", "Welcome") }}</h1>
</template>The composables are useSitecmsContent(), useSitecmsPosts(), useSitecmsPost(slug), useSitecmsEntries(key) and useSitecmsEntry(key, slug). They run on the server through the module's own server route, so the API key never reaches the browser. The helpers (text, image, block, seo) are imported from sitecms-nuxt/helpers. The revalidate webhook clears the Nitro cache, and content from the composables is cached for 60 seconds unless you change cacheSeconds.
How do I connect a SvelteKit site?
sitecms-sveltekit needs SvelteKit 2 or 3 with Svelte 5. The init command saves CMS_API_KEY in .env.local, installs the package, creates three small endpoints under src/routes/api/sitecms/ (revalidate, events, preview) and src/hooks.server.ts with sitecmsHandle if they are missing, creates sitecms.config.ts and adds the prebuild sync. It never overwrites existing files.
npx sitecms-sveltekit initimport { sitecms } from "sitecms-sveltekit/server";
export const load = async (event) => {
const cms = sitecms(event); // reads CMS_API_KEY, takes the preview token from the request
return { content: await cms.getContent() };
};<script lang="ts">
import { editable, text } from "sitecms-sveltekit";
let { data } = $props();
</script>
<h1 {...editable("home", "hero.title")}>{text(data.content, "home", "hero.title", "Welcome")}</h1>Everything that calls sitecms(event) belongs in server code, so the key never reaches the browser. A page that renders on every request shows a change as soon as it is saved or published. A prerendered page (prerender = true) is baked in at build time, so set SITECMS_DEPLOY_HOOK_URL to a deploy hook and the revalidate endpoint rebuilds the site. Live preview works only on pages that render on request.
How do I connect a site without a framework package?
sitecms-js is the core the other packages are built on: a typed client with no dependencies, the helpers, webhook verification, route handlers that take a web-standard Request and return a Response, and the CLI. It runs on Node 18.17 or later and in other runtimes that support Web Crypto. Use it for a plain Node server, Deno, Bun, Cloudflare Workers or any framework that has no package of its own.
npx sitecms-js init <api-key>import { createSitecms, text } from "sitecms-js";
const cms = createSitecms(); // reads CMS_API_KEY
const content = await cms.getContent();
text(content, "home", "hero.title"); // "Welcome"
const posts = await cms.getPosts(); // published posts, newest firstThe handlers in sitecms-js/server (handleRevalidateWebhook, handlePreview, handleEvents) cover the revalidate webhook, live preview and visitor statistics. Where there is no process.env, such as Cloudflare Workers, pass the values explicitly: createSitecms({ apiKey: env.CMS_API_KEY }).
Can I use the REST API directly?
Yes, from any server. The API is at https://sitecms.se/api/v1/site and is authenticated with an x-api-key header. Use it on the server only. To rebuild a site when the customer saves or publishes, paste a deploy hook URL from your host (Cloudflare Pages, Netlify, Render, Vercel) as the revalidate URL under Integration.
curl -s -H "x-api-key: $CMS_API_KEY" https://sitecms.se/api/v1/site/content| Endpoint | Returns |
|---|---|
GET /content | The whole site: { site, pages, services, seo } |
GET /posts | Published posts, newest first, without body text |
GET /posts/{slug} | One post with body (Markdown) and bodyHtml, or 404 |
GET /collections | The custom content types and how many entries each has |
GET /collections/{key}?limit=&offset= | Published entries of one collection, with total, limit and offset |
GET /collections/{key}/{slugOrId} | One entry, or 404 |
GET /health | Checks the key and shows the site and the last sync |
The full API reference is in the Swedish documentation; the endpoints and JSON shapes are the same.
How do I add custom content types (collections)?
Declare a collection under collections in sitecms.config.ts, for example team members or case studies, and run sync (it runs before each build). The sync sends schema version 2 and creates the collection in sitecms. The customer then gets a menu entry for it in the panel with a list, search, create and edit, and drag-and-drop ordering if sortable is on. Limits: 20 collections per site, 30 fields per collection and 2,000 entries per collection. Field types: text, richtext, image, number, boolean, date, select, url.
import { defineConfig } from "sitecms-js"; // or your framework package
export default defineConfig({
pages: [{ slug: "home", title: "Home", blocks: [{ key: "hero.title", label: "Heading" }] }],
collections: [
{
key: "team",
label: "Team",
singular: "Team member",
titleField: "name",
slug: true,
sortable: true,
fields: [
{ key: "name", type: "text", label: "Name", required: true },
{ key: "portrait", type: "image", label: "Portrait" },
{ key: "bio", type: "richtext", label: "About" },
{ key: "department", type: "select", label: "Department", options: ["Sales", "Support"] },
],
},
],
});const team = await cms.getEntries("team", { limit: 20 }); // published entries, limit 1 to 200
const anna = await cms.getEntry("team", "anna"); // slug or id, or nullAn entry is { id, slug, title, sortOrder, publishedAt, updatedAt, data }. Every visible field is in data, and null when empty: rich text as { value, html }, images as { value, alt }, numbers as numbers, booleans as true or false, everything else as strings. Only published entries are returned. The sync never overwrites the customer's entries. A field that you remove from the config is hidden but its data stays until you run sync --prune. There are no relations between collections.
How do I fetch content in another language?
The owner adds languages under Settings in the panel, up to 10 per site including the default language, and the customer translates field by field. On the API side, add ?locale=<code> to the content, posts or collections request, or set locale on the client. Codes follow BCP-47, such as en, en-GB or zh-Hant.
const en = await getContent({ locale: "en" }); // ?locale=en on this call
const cms = createSitecms({ locale: "en" }); // or for every callcurl -s -H "x-api-key: $CMS_API_KEY" "https://sitecms.se/api/v1/site/content?locale=en"- Without
?locale=the response is exactly what it was before, in the default language. - With a language, the response also has
locale,localesanddefaultLocale. - A field with no translation is filled from the default language. Blocks are marked
fallback: true, and services, SEO entries and posts getfallbackandfallbackFields. - An unknown language gives
400with{ "error": …, "code": "locale_unknown" }. - Images, numbers, dates, booleans, slugs and the values of select fields are shared between languages. The option labels of select fields are not translated, but the stored value is stable, so the site can translate the label itself.
What do drafts and scheduled publishing mean for the integration?
Nothing changes in your code. The owner chooses draft mode per site under Settings: new sites have it on, existing sites have it off. With it off, Save goes live at once. With it on, Save stores a draft, and the API returns only published content until someone publishes, immediately or at a scheduled time. The revalidate webhook fires when something goes live, whichever way it got there.
- Live preview in the panel shows saved drafts and unsaved changes, for pages. It uses a short-lived preview token that the package handles for you.
- Posts and collection entries cannot be previewed on the customer's own site, because their endpoints take no preview token. Drafts of them are visible in the panel only.
- Scheduled drafts are published at the chosen time, with a few minutes' delay. A site whose subscription has lapsed does not publish them until it is unlocked.
- Version history keeps the 50 latest versions of each item and everything from the last 90 days.
Which CLI commands are there?
Every package has a command with its own name: sitecms-next, sitecms-astro, sitecms-nuxt, sitecms-sveltekit and sitecms-js. They take the same subcommands.
| Command | What it does |
|---|---|
init [key] | Verifies the key, saves CMS_API_KEY, installs the package, creates the config and files the framework needs, and adds the prebuild sync. Safe to run again: it never overwrites your config. |
sync [--prune] | Sends sitecms.config to sitecms. Missing pages, fields and collections are created and the customer's content is never overwritten. --prune removes what you deleted from the config. |
check | Verifies the key and shows the webhook status. |
doctor | Goes through Node, the package, the key, the config, the connection and the webhook. |
pull | Prints the structure stored in sitecms as JSON. |
Without a subscription (the trial has ended and nobody has paid), the panel is locked and sync skips the sync with a warning and still exits with code 0, so the build goes through.
Frequently asked questions
How do I connect a site to sitecms?
Run the init command for your framework in the project root (for example npx sitecms-next init), paste in the API key from the panel, add CMS_API_KEY where the site is hosted and deploy. Then read content on the server with getContent().
Which frameworks and versions work?
sitecms-next for Next.js (Next.js 14.2 or later with the App Router); sitecms-astro for Astro (Astro 5 or later); sitecms-nuxt for Nuxt (Nuxt 4); sitecms-sveltekit for SvelteKit (SvelteKit 2 or 3 with Svelte 5); sitecms-js for plain JavaScript (no framework needed). The framework packages depend only on the core package sitecms-js, which has no dependencies.
Do changes need a new deploy?
Not on a site that renders on the server. Saving in the panel (or publishing, if the site has draft mode) triggers a signed webhook that clears the cache, so the site shows the change within seconds. A fully static site needs a deploy hook that rebuilds it.
How do I fetch another language?
Add ?locale=en to the content, posts or collections request, or set locale on the client. Fields without a translation come back in the default language, marked fallback. An unknown language gives 400 with the code locale_unknown.
How do I read custom content types?
Declare them under collections in sitecms.config.ts, run sync, and read them with getEntries(key) and getEntry(key, slugOrId), or over the REST API at /api/v1/site/collections.
Does the analytics need a cookie banner?
The built-in analytics sets no cookies and uses no local storage, so it does not need a cookie banner for itself. Your own legal assessment still applies to the rest of your site.
Is this the complete documentation?
This page is a condensed English version. The complete reference, including every API endpoint and the webhook signature format, is in the Swedish documentation.