Skip to content
jshacks.dev
Node.js

Build a Markdown Blog Engine With Node.js

Build a Markdown blog engine in Node.js that serves posts from a folder, caches rendered pages, reloads on change and escapes content safely.

9 min read
Summarize in AI
Flat illustration of an app reading through a fast cache in front of a database, with the Markdown, Node.js, Cloudflare, Redis and NGINX logos.

A static site generator builds every page ahead of time. A blog engine renders them when asked, which suits a site where you want to drop a Markdown file into a folder and see it live without a build step. The two differ in one important way: an engine runs on every request, so it needs caching, safe handling of whatever path a visitor types, and an answer to what happens when a file changes while the server is running. This post builds a small engine on Node.js 26 using node:http, a Map cache keyed by file modification time, node:fs watchers and a minimal Markdown converter that escapes HTML before it formats anything.

The layout

Posts are Markdown files in a posts folder. The file name is the slug, and a small block at the top holds the title and date.

Text
blog/
  server.js
  lib/
    posts.js
    render.js
  posts/
    hello-world.md
    streams-explained.md

A post looks like this:

posts/hello-world.mdText
---
title: Hello World
date: 2026-11-01
---
Welcome. This blog is **plain files** in a folder.

## Why files

You can edit them in any editor, and `git` keeps the history.

The site serves / as an index of posts, newest first, and /<slug> as one post. Anything else is a 404.

Rendering safely

Markdown that comes from your own files is still data, and a stray < in a post must not become markup. Escape first, then apply formatting to the escaped text. This order is the whole security model of the converter.

lib/render.jsJavaScript
function escapeHtml(text) {
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
}

function inline(text) {
  return escapeHtml(text)
    .replace(/`([^`]+)`/g, "<code>$1</code>")
    .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
    .replace(/\*([^*]+)\*/g, "<em>$1</em>")
    .replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2">$1</a>');
}

export function renderMarkdown(source) {
  const lines = source.replaceAll("\r\n", "\n").split("\n");
  const html = [];
  let paragraph = [];
  let inCode = false;
  let code = [];

  const flush = () => {
    if (paragraph.length) html.push(`<p>${inline(paragraph.join(" "))}</p>`);
    paragraph = [];
  };

  for (const line of lines) {
    if (line.startsWith("```")) {
      if (inCode) {
        html.push(`<pre><code>${escapeHtml(code.join("\n"))}</code></pre>`);
        code = [];
      } else {
        flush();
      }
      inCode = !inCode;
      continue;
    }
    if (inCode) {
      code.push(line);
      continue;
    }
    const heading = line.match(/^(#{1,4}) (.+)$/);
    if (heading) {
      flush();
      const level = heading[1].length + 1;
      html.push(`<h${level}>${inline(heading[2])}</h${level}>`);
    } else if (line.trim() === "") {
      flush();
    } else {
      paragraph.push(line.trim());
    }
  }
  flush();
  return html.join("\n");
}

console.log(renderMarkdown("Use `<script>` with **care**.\n\n## Next"));
Text
<p>Use <code>&lt;script&gt;</code> with <strong>care</strong>.</p>
<h3>Next</h3>

Headings are shifted down one level, so a post's ## becomes an <h3>, because the page itself owns the single <h1> for the post title. Fenced code is handled line by line and escaped as a unit, so nothing inside it is treated as formatting. Lists, tables and images are not handled. When your posts need them, swap this one function for a library like marked and keep the rest of the engine.

Loading posts with a cache

Rendering on every request wastes work for pages that rarely change. Cache each post's HTML, and invalidate it when the file's modification time changes. A stat call is far cheaper than reading and rendering.

lib/posts.jsJavaScript
import { readdir, readFile, stat } from "node:fs/promises";
import { join } from "node:path";
import { renderMarkdown } from "./render.js";

const DIR = new URL("../posts/", import.meta.url).pathname;
const SLUG = /^[a-z0-9][a-z0-9-]{0,80}$/;
const cache = new Map();

function parse(source) {
  const match = source.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
  const meta = {};
  if (!match) return { meta, body: source };
  for (const line of match[1].split("\n")) {
    const at = line.indexOf(":");
    if (at > 0) meta[line.slice(0, at).trim()] = line.slice(at + 1).trim();
  }
  return { meta, body: match[2] };
}

export async function getPost(slug) {
  if (!SLUG.test(slug)) return null;
  const file = join(DIR, `${slug}.md`);
  let info;
  try {
    info = await stat(file);
  } catch {
    return null;
  }
  const cached = cache.get(slug);
  if (cached && cached.mtimeMs === info.mtimeMs) return cached.post;

  const { meta, body } = parse(await readFile(file, "utf8"));
  const post = { slug, title: meta.title ?? slug, date: meta.date ?? "", html: renderMarkdown(body) };
  cache.set(slug, { mtimeMs: info.mtimeMs, post });
  return post;
}

export async function listPosts() {
  const names = (await readdir(DIR)).filter((n) => n.endsWith(".md"));
  const posts = await Promise.all(names.map((n) => getPost(n.slice(0, -3))));
  return posts.filter(Boolean).sort((a, b) => b.date.localeCompare(a.date));
}

The SLUG pattern is the defense against path traversal. A request for /../../etc/passwd never reaches the filesystem, because .. and / are not in the allowed set. Validating the slug and then joining it to a fixed directory is far more reliable than trying to sanitize a path after the fact. The cache compares mtimeMs, so saving a post in your editor shows the new version on the next request with no restart and no watcher.

The server

server.jsJavaScript
import { createServer } from "node:http";
import { getPost, listPosts } from "./lib/posts.js";

function layout(title, body) {
  const safe = title.replaceAll("&", "&amp;").replaceAll("<", "&lt;");
  return `<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${safe}</title></head>
<body><header><a href="/">My blog</a></header><main>${body}</main></body></html>`;
}

function send(res, status, html, extra = {}) {
  res.writeHead(status, { "content-type": "text/html; charset=utf-8", ...extra });
  res.end(html);
}

createServer(async (req, res) => {
  if (req.method !== "GET" && req.method !== "HEAD") {
    return send(res, 405, layout("Not allowed", "<p>Method not allowed.</p>"), { allow: "GET, HEAD" });
  }
  const { pathname } = new URL(req.url, "http://localhost");

  if (pathname === "/") {
    const posts = await listPosts();
    const items = posts.map((p) => `<li><a href="/${p.slug}">${p.title.replaceAll("<", "&lt;")}</a> <time>${p.date}</time></li>`);
    return send(res, 200, layout("All posts", `<h1>All posts</h1><ul>${items.join("")}</ul>`));
  }

  const post = await getPost(pathname.slice(1));
  if (!post) return send(res, 404, layout("Not found", "<h1>Not found</h1>"));

  send(res, 200, layout(post.title, `<article><h1>${post.title.replaceAll("<", "&lt;")}</h1><time>${post.date}</time>${post.html}</article>`), {
    "cache-control": "no-cache",
  });
}).listen(3000, () => console.log("blog on http://localhost:3000"));

Request /hello-world and the first call reads and renders the file, while later calls return the cached HTML after one stat. The cache-control: no-cache header does not turn browser caching off. It tells the browser to revalidate every time, which is cheap, and it means a new version of a post is never hidden behind a stale copy. Adding an etag made from the file's mtimeMs would let the server answer 304 with no body.

Look at the result.

Shell
curl -s localhost:3000/hello-world
Text
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello World</title></head>
<body><header><a href="/">My blog</a></header><main><article><h1>Hello World</h1><time>2026-11-01</time><p>Welcome. This blog is <strong>plain files</strong> in a folder.</p>
<h3>Why files</h3>
<p>You can edit them in any editor, and <code>git</code> keeps the history.</p></article></main></body></html>

An unknown path answers cleanly.

Shell
curl -s -o /dev/null -w "%{http_code}\n" localhost:3000/..%2f..%2fetc%2fpasswd
Text
404

The index and the cost of listing

listPosts calls getPost for every file, so the index costs one stat per post once the cache is warm. That is fine for a few hundred posts. For thousands, build the list once at startup, keep it in memory and refresh it with fs.watch on the folder, which reports changes so you rebuild only when something happens. A watcher has caveats: events can arrive twice, editors that save through a temporary file produce renames, and recursive watching is not consistent on every platform, so treat events as a hint to re-scan and not as the source of truth.

Putting it to use

Two small additions turn this into a usable blog. An RSS feed is another route that maps listPosts() to XML and escapes every field. A sitemap works the same way. Both reuse the cache, so they cost almost nothing.

For deployment, run the server under a process manager and put a reverse proxy such as nginx in front, with a short cache on the HTML so a traffic spike hits the proxy and not Node.js. Keep the posts folder in git and deploy by pulling, and the cache will notice changed files on its own.

Where this design stops

The converter is deliberately small, so features like footnotes or tables need a library. Drafts need a front matter flag you filter on. Comments, search and tags are each a project. And one process holds one cache, which is fine behind a proxy for a personal blog and unnecessary to share. If you outgrow the engine, the posts are plain Markdown files, so moving to a static generator or a CMS later costs you nothing.

Making it fast enough

For a personal blog you will never notice the cost of this engine, but it is useful to know where the time goes, so you can decide when to care. A request for a cached post does one stat and one string concatenation. A request for an uncached post adds a file read and a render, which for a 3,000-word post is a fraction of a millisecond on ordinary hardware. The expensive work is the network, not your code.

So the first speed-up is outside the program. Put a reverse proxy in front and let it cache the HTML for ten seconds. A burst of ten thousand visitors then reaches Node.js as a request or two per ten seconds, and the cache you wrote inside the process hardly matters. If you cannot run a proxy, add an etag header built from mtimeMs and return a 304 when the browser sends it back, which saves the response body even though the request still arrives.

The second speed-up is compression. HTML compresses to a fraction of its size, and a text-heavy page of 40 KB can shrink below 10 KB. Let the proxy do it, or use zlib.gzip in the response if you serve directly. Remember to set vary: accept-encoding so a shared cache does not hand a compressed copy to a client that cannot read it.

The third is knowing what you do not need. A blog does not need a database, a build pipeline or a framework, and each one you skip is a piece that cannot break at midnight. The honest cost of this approach is the work you take on yourself: security of the converter, correct headers and a deploy routine. If you would rather not own those, a static generator moves the same Markdown files to a place where those problems mostly vanish, because there is no code running at request time.

Whatever you choose, keep the content as plain Markdown with simple front matter. That file format is the part that lasts. Engines come and go, and a folder of text files moves between all of them.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.