All articles

Building a Markdown Blog on Fresh with TanStack Markdown

Sean Merriam ·

How this blog moved from a JSON file of pre-rendered HTML to plain Markdown files, and the one build problem that made the obvious loader break in production.

Until last week, every article on this site lived in a single JSON file. Each post was an object with a title, a date, a hand-written dateLabel, and an array of sections, and each section carried a blob of pre-rendered HTML. It worked, but writing a post meant producing HTML somewhere else and pasting it into a string. Nobody wants to review a diff of escaped <p> tags.

What I wanted was the MDX workflow without MDX: a Markdown file per post, a little metadata at the top, and the site doing the rest. MDX doesn't fit a Fresh project cleanly, and I didn't need components inside posts anyway. Plain Markdown was enough, so that's what I built, with TanStack Markdown doing the rendering.

The shape of it

The whole system is four pieces:

  • src/blog/posts/*.md: one file per post. The file name is the slug, so hello-world.md is served at /blog/hello-world.
  • src/blog/mod.ts: the loader. It finds the posts, parses their metadata, renders the Markdown to HTML, hides drafts and sorts by date.
  • routes/blog/index.tsx and routes/blog/[slug].tsx: the list page and the post page.
  • A dozen lines of Vite config, which I'll get to, because it's the only part that wasn't obvious.

Two dependencies cover the actual work:

deno add npm:@tanstack/markdown jsr:@std/front-matter

Frontmatter and body, handled separately

A post looks like this:

---
title: Building with Deno Fresh
description: Creating a lightweight blog with Fresh.
date: 2026-11-17
tags:
  - deno
  - fresh
draft: false
---

Fresh makes it easy to build fast, server-rendered websites...

I kept the metadata and the article apart on purpose. @std/front-matter splits off the YAML block and parses it; TanStack Markdown only ever sees the body. Each tool does one small job, and neither needs to know about the other.

import { extract } from "@std/front-matter/yaml";
import { renderHtml } from "@tanstack/markdown/html";

const { attrs, body } = extract<Record<string, unknown>>(source);
const html = renderHtml(body);

renderHtml takes a Markdown string and returns an HTML string, which is exactly what a server-rendered page wants. Nothing is shipped to the browser.

Two details from the defaults turned out to matter. Raw HTML in a post is escaped rather than passed through, and links with unsafe schemes such as javascript: are dropped. The rendered HTML goes into the page with dangerouslySetInnerHTML, so I was glad that the safe behaviour is the one you get without asking. Headings also get id attributes generated from their text, so every section of a post is linkable.

Don't trust the frontmatter

YAML is helpful in ways you don't always want. An unquoted date: 2026-11-17 doesn't come back as a string. It comes back as a JavaScript Date, and the first time the loader tried to sort posts with localeCompare it threw. The loader now accepts either form and normalises to a YYYY-MM-DD string:

function toIsoDate(value: unknown, slug: string): string {
  if (value instanceof Date && !Number.isNaN(value.getTime())) {
    return value.toISOString().slice(0, 10);
  }
  if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
    return value;
  }
  throw new Error(`Post "${slug}": "date" must be a YYYY-MM-DD date`);
}

The same goes for the other fields. title, description and date are required, tags must be a list of strings, and draft must be a boolean. A post that breaks any of those rules throws with the slug in the message. Because every post is parsed once when the server starts, a typo in frontmatter fails the build instead of turning into a 500 on the one page that has it.

The part that broke: reading files in production

The first version of the loader did the obvious thing. It built a URL to the posts folder relative to the module and read the directory:

const POSTS_DIR = new URL("./posts/", import.meta.url);

for await (const entry of Deno.readDir(POSTS_DIR)) {
  // ...
}

That works in development, and it would work in a plain Deno server. It does not work in a Fresh 2 production build. Fresh builds with Vite, and Vite bundles server code into _fresh/server/. Once mod.ts has been bundled, import.meta.url points at a generated file inside _fresh/, and ./posts/ next to it doesn't exist. Every post would have been a 404 on the live site.

The fix is to stop reading files at runtime and let the bundler include them. Vite's import.meta.glob does that:

const sources = import.meta.glob<string>("./posts/*.md", {
  import: "default",
  eager: true,
});

Normally you'd add query: "?raw" to get each file as a string. Fresh's Vite plugin resolves module IDs itself and the query didn't survive. The build failed trying to parse a Markdown file as JavaScript. So I added a small plugin that runs before Fresh's and turns any .md import into a string export:

function markdownSource(): Plugin {
  return {
    name: "markdown-source",
    enforce: "pre",
    async load(id) {
      const path = id.split("?")[0];
      if (!path.endsWith(".md")) return null;
      this.addWatchFile(path);
      const source = await Deno.readTextFile(path);
      return `export default ${JSON.stringify(source)};`;
    },
  };
}

A side benefit is that the running server needs no file-system permission to serve the blog, since the posts are part of the bundle. The cost is that adding a post needs a rebuild, which on a deployed site happens on every push anyway.

Routes

With the loader returning plain data, the routes are short. The post page looks the slug up and returns a 404 for anything unknown or still marked as a draft:

export default define.page(function BlogPostPage(ctx) {
  const post = getPost(ctx.params.slug);
  if (!post) throw new HttpError(404, "Article not found");

  return <BlogPost post={post} />;
});

getPost also checks the slug against ^[a-z0-9-]+$ before looking anything up. With the posts bundled in, there's no file path to traverse, but the check costs nothing and makes the contract explicit.

The list page maps over getPosts(), and the Writing section on the homepage uses the same function to show the latest four. Each card's reading time is estimated from the word count of the body, which replaced another value that used to be typed by hand.

Old URLs had the form /blog/posts/:slug. A one-handler route returns a 301 to /blog/:slug, so existing links keep working.

Moving the old posts

The four existing articles were the only content that had to survive. Their HTML used just a handful of tags — paragraphs, code, strong, em and one code block — so a short one-off script turned them into Markdown. The section titles became ## headings, bare "Introduction" headings were dropped because the page header already introduces each post, and the code block got an erlang language hint. Each one now reads as a normal Markdown file you could open and edit.

What it's like to write a post now

Create a file in src/blog/posts/, add the frontmatter, write. Set draft: true to keep it off the site while it's in progress. Open a pull request and the diff is the article itself. This post was written that way.

Extensions are next. TanStack Markdown has callouts, tabs and heading anchors behind separate imports, and the loader is the only place that needs to change to turn them on.

Back to writing