Diego Betto
Photo by Karl Abuid on Unsplash

Diego Betto · ·17 min di lettura

Headless CMS, Jamstack and AI personalization

Headless architecture with Astro: static pages, live data where it matters, embedding-based recommendations and personalization mindful of GDPR and AI Act.

Condividi:XLinkedInFacebookWhatsApp

It’s a perfectly reasonable request: “on the homepage, show returning visitors the articles they care about”. On a monolithic CMS the shortest route is a plugin that reads a cookie and assembles the page on the server. It works, but from that moment the homepage differs for every visitor, the CDN cache is useless and every visit repeats queries, templates and external calls.

The problem comes from editing, rendering and personalization living in the same place: touch one and you drag the others along. A headless architecture separates them and allows a simple rule: static by default, dynamic only in small islands, AI where it adds value and only on data you’re allowed to use.

Let’s see how that translates into code with Astro: content loaded at build time, live data, server islands, recommendations with embeddings. And then the part that usually shows up too late: what the GDPR and the AI Act say.

Headless and Jamstack in 2026: what they really mean

Headless means the CMS manages content and exposes it through APIs, without deciding how it’s displayed. Jamstack is the name under which the complementary model became popular: a separate front-end that generates ahead of time everything it can, serves it from a CDN and calls APIs only for the rest.

The benefit isn’t cosmetic. A pre-generated page is a file: fast response, no code to run on each request, and an unreachable CMS doesn’t take the site down. In exchange you have to handle two things the monolith gave you for free: draft previews and updating pages when content changes.

There are essentially three families of CMS.

Family Examples Where content lives What to evaluate
SaaS Sanity, Contentful, Storyblok, Hygraph The vendor’s platform Cost over time, data portability
Open source, self-hosted Strapi, Payload, Directus Your database Upgrades, backups, hosting
Git-based Decap, Keystatic, TinaCMS Files in the repository Editorial workflow, number of files

A note on Payload, because the question comes up when choosing: its team joined Figma, which stated that the project stays open source.

💬 Opinione personale

Pick the CMS starting from the people who write, not from the feature table. How do you preview? Who approves? What happens when two people edit the same text? A technically elegant CMS that the editorial team avoids is a failed project.

Build-time content: Astro’s content layer

In Astro, content flows through collections, defined with defineCollection and fed by a loader. This blog uses the glob loader on MDX files, with a generateId that builds ids from the path. With a CMS the structure stays the same: only the loader changes.

The simplest case is an inline loader, an async function returning an array of objects with an id. The endpoint in the example is made up: replace it with your CMS’s REST or GraphQL API.

// src/content.config.ts
import { defineCollection } from "astro:content";
import { z } from "astro/zod";

interface CmsArticle {
  slug: string;
  title: string;
  description: string;
  body: string;
  tags: string[];
  publishedAt: string;
}

const articles = defineCollection({
  loader: async () => {
    // CMS_URL is an environment variable; /api/articles is a sample endpoint
    const response = await fetch(`${import.meta.env.CMS_URL}/api/articles`);

    // Better to fail the build than to publish an empty site
    if (!response.ok) throw new Error(`CMS unreachable: HTTP ${response.status}`);

    const items: CmsArticle[] = await response.json();
    return items.map((item) => ({ ...item, id: item.slug }));
  },
  schema: z.object({
    slug: z.string(),
    title: z.string(),
    description: z.string(),
    body: z.string(),
    tags: z.array(z.string()).default([]),
    publishedAt: z.coerce.date(),
  }),
});

export const collections = { articles };

The Zod schema is the contract between editors and front-end. If someone makes a field optional in the CMS, you find out through a readable build error instead of an undefined in production.

Pages are generated as for any collection:

---
// src/pages/articles/[slug].astro
import { getCollection } from "astro:content";

export async function getStaticPaths() {
  const articles = await getCollection("articles");
  return articles.map((article) => ({
    params: { slug: article.id },
    props: { article },
  }));
}

const { article } = Astro.props;
---

<h1>{article.data.title}</h1>
<p>{article.data.description}</p>

To update the site you use a webhook: when content is published, the CMS calls a hosting platform URL that starts a new build. It’s a dull, robust mechanism. Its limit is time: between “Publish” and the page going live you wait for the whole build.

Live data: live collections and caching

Prices, availability, scores: some data can’t wait for a build. Since version 6 Astro has live collections, which query the source at request time through an API similar to regular collections. The examples follow Astro 7.

They are defined in a dedicated file, src/live.config.ts, using a LiveLoader: an object with name, loadCollection and loadEntry. The remote API here is fictional too.

// src/loaders/products.ts
import type { LiveLoader } from "astro/loaders";

interface Product extends Record<string, unknown> {
  name: string;
  price: number;
}

type ProductDto = Product & { id: string };

export function productsLoader(baseUrl: string): LiveLoader<Product> {
  const toEntry = ({ id, ...data }: ProductDto) => ({
    id,
    data,
    cacheHint: { tags: ["products", `product-${id}`] },
  });

  return {
    name: "products-loader",
    async loadCollection() {
      const response = await fetch(`${baseUrl}/products`);
      if (!response.ok) return { error: new Error(`HTTP ${response.status}`) };

      const products: ProductDto[] = await response.json();
      return { entries: products.map(toEntry) };
    },
    async loadEntry({ filter }) {
      // With getLiveEntry("products", "abc") the filter is { id: "abc" }
      const { id } = filter as { id: string };
      const response = await fetch(`${baseUrl}/products/${encodeURIComponent(id)}`);
      if (!response.ok) return { error: new Error(`HTTP ${response.status}`) };

      return toEntry(await response.json());
    },
  };
}
// src/live.config.ts
import { defineLiveCollection } from "astro:content";
import { productsLoader } from "./loaders/products";

const products = defineLiveCollection({
  loader: productsLoader(import.meta.env.CMS_URL),
});

export const collections = { products };

loadCollection also receives an optional filter, useful for filtering on the API side. Errors aren’t thrown: the loader returns { error } and the page decides what to do.

---
// src/pages/products/[id].astro
import { getLiveEntry } from "astro:content";

export const prerender = false;

const { entry, error, cacheHint } = await getLiveEntry("products", Astro.params.id!);

if (error || !entry) {
  return new Response("Product unavailable", { status: 404 });
}

if (cacheHint) Astro.cache.set(cacheHint);
Astro.cache.set({ maxAge: 300, swr: 60 });
---

<h1>{entry.data.name}</h1>
<p>€{entry.data.price}</p>

To keep it short every error becomes a 404 here; in a real project, tell “doesn’t exist” apart from “the backend isn’t answering”. The first Astro.cache.set call records the tags suggested by the loader, the second sets five minutes of freshness plus one minute of stale-while-revalidate.

Caching is configured once:

// astro.config.mjs
import { defineConfig, memoryCache } from "astro/config";
// import your platform's adapter

export default defineConfig({
  // adapter: ...,
  cache: { provider: memoryCache() },
  routeRules: {
    "/products/[...slug]": { maxAge: 3600, tags: ["products"] },
  },
});

And when the CMS reports a change, instead of rebuilding you invalidate by tag:

// src/pages/api/revalidate.ts
import type { APIRoute } from "astro";

export const prerender = false;

export const POST: APIRoute = async ({ request, cache }) => {
  const secret = import.meta.env.WEBHOOK_SECRET;
  if (!secret || request.headers.get("authorization") !== `Bearer ${secret}`) {
    return new Response("Unauthorized", { status: 401 });
  }

  await cache.invalidate({ tags: ["products"] });
  return new Response(null, { status: 204 });
};

Configure the CMS webhook to send Content-Type: application/json: Astro checks the origin of requests and, in my test, a POST with neither Origin nor a content type gets a 403 before reaching your code. Inside a page the same operation is Astro.cache.invalidate({ tags: ["products"] }). Keep in mind that memoryCache lives in process memory: with several instances each one has its own copy.

⚠ Attenzione

All of this requires on-demand rendering, hence an adapter: it doesn’t work on a purely static site. Without a configured cache provider, Astro.cache.set has no effect and cache headers must be set by hand, for instance with Astro.response.headers.set.

Server islands: the page stays static, the personal part doesn’t

For the original request, recommended articles for returning visitors, there’s no need to make the page dynamic. You only need to make that block dynamic. With server islands you add server:defer to an Astro component: the page is served right away with a placeholder and the island’s content arrives with a separate request.

---
// src/pages/index.astro
import Recommendations from "../components/Recommendations.astro";
---

<h1>Latest articles</h1>

<Recommendations server:defer>
  <p slot="fallback">Preparing suggestions…</p>
</Recommendations>

The island reads a first-party cookie with recently read tags and picks accordingly. Without the cookie, it shows the latest articles.

---
// src/components/Recommendations.astro
import { getCollection } from "astro:content";

const recent = new Set(Astro.cookies.get("recent_tags")?.value.split(",") ?? []);
const score = (tags: string[]) => tags.filter((tag) => recent.has(tag)).length;

const articles = (await getCollection("articles"))
  .sort(
    (a, b) =>
      score(b.data.tags) - score(a.data.tags) ||
      b.data.publishedAt.getTime() - a.data.publishedAt.getTime(),
  )
  .slice(0, 3);
---

<h2>{recent.size > 0 ? "Picked for you" : "Worth reading"}</h2>
<ul>
  {articles.map((a) => <li><a href={`/articles/${a.id}/`}>{a.data.title}</a></li>)}
</ul>

The browser writes the cookie, only if the user has consented, and with an expiry:

// src/scripts/remember-tags.ts
export function rememberTags(tags: string[], hasConsent: boolean) {
  if (!hasConsent) return;

  const value = encodeURIComponent(tags.slice(0, 5).join(","));
  const thirtyDays = 60 * 60 * 24 * 30;
  document.cookie = `recent_tags=${value}; Path=/; Max-Age=${thirtyDays}; SameSite=Lax; Secure`;
}

The containing page stays identical for everyone, so it remains cacheable on the CDN. Three details to remember:

  • you need an adapter, because the island is rendered on the server;
  • props must be serializable and travel in the query string of a GET request (if the URL gets too long Astro switches to POST): keep them small and free of personal data;
  • inside the island Astro.url isn’t the address of the visited page; if you need it, derive it from the Referer header.

An island that depends on a cookie must not end up in a shared cache. Server and client islands solve different problems: <Recommendations server:defer /> runs code on the server and sends HTML, while client:visible sends JavaScript to the browser to make a component interactive.

Recommendations and semantic search with embeddings

Tags work as long as editors assign them carefully. Embeddings go a step further: they turn text into a vector, and texts with similar meaning end up close to each other. Closeness is measured with cosine similarity.

With AI SDK 7 you only need embedMany, embed and cosineSimilarity. A script run before the build computes vectors for title, description and an excerpt of the body, and saves them as JSON:

// scripts/build-embeddings.ts
import { writeFile } from "node:fs/promises";
import { cosineSimilarity, embedMany } from "ai";
import { openai } from "@ai-sdk/openai";

interface Article {
  slug: string;
  title: string;
  description: string;
  body: string;
}

const response = await fetch(`${process.env.CMS_URL}/api/articles`);
if (!response.ok) throw new Error(`CMS: HTTP ${response.status}`);
const articles: Article[] = await response.json();

const { embeddings } = await embedMany({
  model: openai.embedding("text-embedding-3-small"),
  values: articles.map((a) => `${a.title}\n${a.description}\n${a.body.slice(0, 2000)}`),
});

const index = articles.map((article, i) => ({
  slug: article.slug,
  title: article.title,
  embedding: embeddings[i],
}));

// "Related posts": everything is computed now, no AI at runtime
const related = Object.fromEntries(
  index.map((item) => [
    item.slug,
    index
      .filter((other) => other.slug !== item.slug)
      .map((other) => ({
        slug: other.slug,
        title: other.title,
        score: cosineSimilarity(item.embedding, other.embedding),
      }))
      .sort((a, b) => b.score - a.score)
      .slice(0, 3),
  ]),
);

await writeFile("src/data/embeddings.json", JSON.stringify(index));
await writeFile("src/data/related.json", JSON.stringify(related, null, 2));

The related.json file is imported by the article page and ends up in the static HTML. This is my favorite kind of “AI”: no model call during the visit and no personal data, because the recommendation depends on what you’re reading, not on who you are.

Semantic search does need a runtime step, because the query isn’t known in advance. You compute its embedding with the same model and compare it with the vectors you already have:

// src/pages/api/search.ts
import type { APIRoute } from "astro";
import { z } from "astro/zod";
import { cosineSimilarity, embed } from "ai";
import { openai } from "@ai-sdk/openai";
import index from "../../data/embeddings.json";

export const prerender = false;

const Body = z.object({ query: z.string().trim().min(3).max(200) });

export const POST: APIRoute = async ({ request }) => {
  const body = Body.safeParse(await request.json().catch(() => null));
  if (!body.success) return Response.json({ error: "Invalid query" }, { status: 400 });

  const { embedding } = await embed({
    model: openai.embedding("text-embedding-3-small"),
    value: body.data.query,
  });

  const results = index
    .map(({ slug, title, embedding: vector }) => ({
      slug,
      title,
      score: cosineSimilarity(embedding, vector),
    }))
    .sort((a, b) => b.score - a.score)
    .slice(0, 5);

  return Response.json({ results });
};

This endpoint is public and every call has a cost: besides validation it needs a rate limit and the same care that applies to Server Actions. Also consider that the query is free text written by the user and it gets sent to the provider. If you use AI Gateway, instead of openai.embedding(...) you can pass the id as a string, "openai/text-embedding-3-small".

💡 Consiglio

In my opinion, on an editorial site a vector database only becomes useful beyond a few thousand documents. Below that, a JSON file and a loop are enough and don’t add a service to run. The real threshold depends on vector size and acceptable latency: measure it.

Generated variants, but at build time

Another sensible use is producing variants in advance for a few declared segments, say one summary for beginners and one for experienced readers. With structured output the model has to match a schema:

// scripts/summaries.ts
import { generateText, NoObjectGeneratedError, Output, type LanguageModel } from "ai";
import { z } from "zod";

const schema = z.object({
  summary: z.string().max(400),
  prerequisites: z.array(z.string()).max(3),
});

export async function summarize(
  model: LanguageModel,
  article: string,
  audience: "beginner" | "expert",
) {
  try {
    const result = await generateText({
      model,
      output: Output.object({ schema }),
      prompt: `Summarize for ${audience} readers:\n\n${article}`,
    });
    return result.output;
  } catch (error) {
    // AI_NoObjectGeneratedError: the answer doesn't match the schema
    if (NoObjectGeneratedError.isInstance(error)) return null;
    throw error;
  }
}

The variants go through human review, get saved and are served as files. Conversational interfaces and agents are a different story, which I covered in the article on AI components in the front-end. If you’d rather keep the user’s text on the device, embeddings can be computed in the browser: the starting point is WebGPU and client-side AI. Remember that query and index must use the same model.

Personalization: what the GDPR and the AI Act say

This is where architectural choices become legal choices too.

GDPR. Building an interest profile is profiling, and like any processing it needs a legal basis (Article 6). If the profiling serves direct marketing, the data subject has the right to object (Article 21). Article 22 concerns decisions based solely on automated processing that produce legal effects or similarly significant ones: suggesting an article usually doesn’t qualify, but deciding prices or eligibility for a service can.

ePrivacy. Article 5(3) of Directive 2002/58/EC requires consent to store or read cookies and identifiers on the device when they aren’t strictly necessary. The recently-read-tags cookie is a good candidate: that’s why the example writes it only after consent.

AI Act. The transparency obligations of Article 50 apply from 2 August 2026 and weren’t postponed by the Digital Omnibus: people interacting with an AI system, a chatbot for instance, must be told. Article 50(2) also requires machine-readable marking of generated content; for systems already on the market there’s reportedly a grace period until 2 December 2026, but this comes from secondary sources, so verify it. Content recommendation isn’t high-risk per se and, according to the Digital Omnibus, high-risk obligations have been postponed anyway to December 2027 and August 2028, depending on the category.

From rules to design decisions:

  • prefer contextual or content-based recommendations, which need no profile;
  • if a profile is needed, keep it first-party, minimal and with an expiry;
  • offer a “not personalized” switch that actually works;
  • don’t send personal data to the embedding provider;
  • explain next to the block why that content is shown.

⚠ Attenzione

This isn’t legal advice. The right legal basis, whether you need an impact assessment and the wording of your privacy notice depend on the specific case: involve whoever handles privacy before collecting the first piece of data, not after.

Performance and SEO

Personalized fragments arrive after loading and aren’t part of the initial HTML that crawlers and AI engines read. Use that as a criterion: canonical content lives in the static page, personalization adds to it and never replaces it. Title, body, links between articles and structured data must be there even for those who don’t run a single line of JavaScript. That makes build-time related posts doubly useful.

On the performance side, reserve for the placeholder the space the island will take, so the layout doesn’t shift. And don’t put the LCP element in an island: you’d be waiting for an extra request for exactly the most important thing. If you work with a React front-end, similar reasoning about the server/client boundary applies to React Server Components.

Finally, there’s a positive side effect: fewer repeated server renders mean less work, and so less energy, even though byte-based estimates don’t capture it directly. I discuss that in the article on digital sustainability.

Checklist

  • CMS chosen together with editors, draft preview actually tried
  • Zod schema for every collection, build failing when the API doesn’t answer
  • Publish webhook wired to the build or to tag invalidation
  • On-demand rendering only on the routes that need it
  • Canonical content and internal links in the static HTML
  • Personalized islands with a sized fallback, kept out of shared caches
  • Precomputed embeddings, search endpoint with validation and rate limit
  • Consent before non-essential cookies, a switch to turn personalization off
  • Users told when they’re talking to an AI system

Frequently asked questions

❓ Do I need a headless CMS for a blog?

Often not. If the authors are comfortable with Markdown and Git, files in the repository are the simplest solution. A headless CMS makes sense when you need an editing interface, there are several authors with different roles or the same content feeds multiple channels.

❓ Live collections or rebuild via webhook?

The rebuild is the default choice: static site, no server to run. Live collections are for data that changes faster than a build takes, or for when you can’t generate every page in advance. They require an adapter and a caching strategy.

❓ Do AI recommendations require consent?

It depends on the data, not on the use of AI. Related posts computed from content, without reading or storing anything on the device, create no profile. If you use non-essential cookies or identifiers to personalize, you need consent, plus a legal basis for the processing.

❓ What's the difference between server islands and client islands?

A server island, marked with server:defer, is rendered on the server after the page loads and can read cookies and private data. A client island, with directives such as client:visible, hydrates a component in the browser to make it interactive.

Conclusion

Before adding personalization to a site, try describing in one sentence which data you use, where it’s read and what someone who refuses gets to see. If the answer is “no data, just the article they’re reading”, you already have the fastest, cheapest and most defensible version. If you need more, keep it in a small island you can switch off: the rest of the site can remain a set of files served by a CDN, which is a great place to be.

References:

Condividi:XLinkedInFacebookWhatsApp
Diego Betto

Written by

Diego Betto

Co-Founder & CTO at PAPION. Senior software engineer with AI skills: React, TypeScript, Node.js, LLM and AI agent integration, and application security.