Building Markdown-Driven Content Engines: AST Parsing, Sanitization, and Static Generation
An architectural guide to headless content architecture: parsing Markdown ASTs, eliminating XSS vulnerabilities with sanitization pipelines, and scaling static Next.js sites.
By Robin Singh · Published · Last reviewed · 3 min read
For content-rich technical platforms, engineering documentation sites, and high-conversion blogs, traditional monolithic Content Management Systems (CMS) introduce unnecessary database latency, security vulnerabilities, and deployment bloat. A modern Markdown-driven architecture couples developer-friendly version control (git) with deterministic static site generation.
At Palmate Solutions, our web development engineers build high-performance web applications that leverage Markdown pipelines to achieve sub-100ms TTFB and perfect 100/100 Core Web Vitals scores. When drafting articles or verifying HTML AST transformations, you can preview and validate your documents in real time using our Markdown Previewer & HTML Converter.
1. Why Git-Backed Markdown Wins Over Traditional CMS
Traditional database-backed CMS platforms (WordPress, Drupal) suffer from structural architectural liabilities:
- Database Query Latency: Serving dynamic database-rendered pages requires runtime SQL roundtrips and Redis caching layers.
- Attack Surface: Dynamic administrative dashboards and plugin ecosystems represent over 80% of web CMS attack vectors.
- Weak Audit Trails: Database-stored content lacks atomic change tracking, branch previews, and peer pull-request review workflows.
By contrast, a file-backed Markdown architecture stores content as version-controlled .md files alongside the application source code:
- Atomic Branch Previews: Marketing copy and engineering documentation undergo peer review via GitHub Pull Requests with automated staging previews.
- Pure Static Compilation: Content is parsed at build time into pre-rendered HTML and JSON, deployed to edge CDNs with zero runtime server latency.
- Decoupled Architecture: If the front-end framework changes, content files remain portable, standards-compliant plain text.
2. The Modern Markdown Compilation Pipeline: Unified, Remark & Rehype
Modern JavaScript and TypeScript content engines rely on the unified collective ecosystem, which separates content processing into three distinct phases:
[Markdown Text]
│
▼ (Remark: parse to mdast)
[Markdown Abstract Syntax Tree (mdast)]
│
▼ (remark-rehype: transform)
[HTML Abstract Syntax Tree (hast)]
│
▼ (Rehype: syntax highlight, autolinks, sanitize)
[Sanitized HTML Abstract Syntax Tree]
│
▼ (rehype-stringify)
[Production HTML String]
Phase 1: Markdown Abstract Syntax Tree (mdast)
The parser transforms raw Markdown tokens into a structured syntax tree. This allows custom remark plugins to intercept headings, embed interactive components, calculate reading times, and validate internal cross-references.
Phase 2: HTML Abstract Syntax Tree (hast)
The mdast tree is mapped to an HTML AST. Plugins like rehype-slug inject deterministic IDs to headings, rehype-autolink-headings generates anchor links, and rehype-prism or shiki highlights code snippets with zero client-side JavaScript cost.
Phase 3: Sanitization and Security
Allowing arbitrary HTML inside Markdown introduces acute Cross-Site Scripting (XSS) risks. A strict sanitization schema ensures that tags like <script>, <iframe>, or malicious onerror event handlers are stripped before rendering.
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
import remarkRehype from "remark-rehype";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import rehypeStringify from "rehype-stringify";
export async function compileMarkdownToHtml(rawMd: string): Promise<string> {
const file = await unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkRehype)
.use(rehypeSanitize, {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
code: [["className", /^language-./]],
},
})
.use(rehypeStringify)
.process(rawMd);
return String(file);
}
3. Extracting and Validating Frontmatter Schemas
Metadata (titles, descriptions, publishing dates, author credentials, related tools, and tags) should be defined as YAML frontmatter at the top of each document.
In production engines, never access raw untyped frontmatter. Validate every document at build time using runtime schemas like Zod:
import { z } from "zod";
export const ArticleFrontmatterSchema = z.object({
title: z.string().min(10).max(100),
description: z.string().min(50).max(250),
slug: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
publishedAt: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
updatedAt: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
category: z.enum(["web-development", "cloud-devops", "security", "apis-integrations"]),
relatedTools: z.array(z.string()).default([]),
featured: z.boolean().default(false),
});
If an author misspells a category name or violates date format rules, the CI/CD pipeline immediately fails the build, preventing broken routes or missing metadata from hitting production.
4. Best Practices for High-Performance Content Sites
- Deterministic Build-Time RSS and Sitemaps: Generate XML sitemaps and Atom/RSS feeds automatically from compiled Markdown files to accelerate search engine indexing.
- Dynamic OpenGraph Images: Automatically generate customized SVG/PNG social preview cards containing the article title, author, and reading time using Next.js
@vercel/ogor Node canvas rendering. - Structured Schema.org Markup: Inject
BlogPostingorArticleJSON-LD schemas into page headers to qualify for Google rich snippet search results.
Before launching a new content-driven platform or major redesign, review every pre-flight deployment requirement using our interactive Website Launch Checklist.
