@bliztek/mdx-utils
v2.0.0
Published
Zero-dependency MDX content utilities for read time calculation and file discovery
Downloads
35
Maintainers
Readme
@bliztek/mdx-utils
Zero-dependency MDX content utilities for read time calculation and file discovery.
Installation
npm install @bliztek/mdx-utilsUsage
Pure Utilities (any JS environment)
import {
calculateReadTime,
sortByDateDescending,
stripMdxSyntax,
} from "@bliztek/mdx-utils";
// Calculate read time from raw MDX content
const { minutes, words } = calculateReadTime(mdxContent);
// => { minutes: 5, words: 1190 }
// Custom words per minute
const { minutes } = calculateReadTime(technicalDoc, { wordsPerMinute: 150 });
// Strip MDX syntax for excerpts, search indexes, or OG descriptions
const plainText = stripMdxSyntax(mdxContent);
// Sort items by date (newest first)
const sorted = sortByDateDescending(posts, (post) => post.date);Node.js Utilities
import { getContentSlugs, readMdxFile } from "@bliztek/mdx-utils/node";
// Get all MDX slugs from a directory
const slugs = await getContentSlugs("./content/blog");
// => ["my-first-post", "another-post"]
// Include .md files too
const all = await getContentSlugs("./content", {
extensions: [".mdx", ".md"],
});
// Recursively search nested directories
const nested = await getContentSlugs("./content/blog", { recursive: true });
// => ["my-first-post", "2024/year-in-review"]
// Read an MDX file
const content = await readMdxFile("./content/blog/my-first-post.mdx");API
calculateReadTime(content, options?)
Calculates estimated read time for MDX/markdown content. Strips export blocks, import statements, JSX tags, and markdown syntax before counting words.
Returns { minutes: number, words: number } — minutes is always at least 1.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| wordsPerMinute | number | 238 | Reading speed to use for calculation |
stripMdxSyntax(content)
Strips MDX/markdown syntax from content, returning plain text. Removes export blocks, import statements, JSX tags, and markdown formatting characters. Useful for generating excerpts, search indexes, or OpenGraph descriptions from raw MDX.
sortByDateDescending(items, getDate)
Sorts items by date in descending order (newest first). Returns a new array without mutating the original. The getDate callback should return a date string parseable by new Date().
getContentSlugs(dirPath, options?)
Reads a directory and returns slugs (filenames without extension) of matching content files. When recursive is true, slugs from subdirectories include their relative path (e.g., "2024/my-post").
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| extensions | string[] | [".mdx"] | File extensions to include |
| recursive | boolean | false | Search subdirectories |
readMdxFile(filePath)
Reads a file and returns its content as a UTF-8 string.
Collections
For content trees with more than a flat directory of posts — game guides, docs, multi-product changelogs — use createMdxCollection to get a typed handle that walks the tree, parses frontmatter, and (optionally) validates against a schema.
Flat blog
import { createMdxCollection } from "@bliztek/mdx-utils/node";
const posts = createMdxCollection({ root: "content/blog" });
const all = await posts.getAll();
const post = await posts.get({ slug: "my-first-post" });Typed frontmatter
Pass a type parameter to make every getter return your shape:
interface PostFrontmatter {
title: string;
publishedAt: string;
description?: string;
aliases?: string[];
relatedSlugs?: string[];
}
const posts = createMdxCollection<PostFrontmatter>({
root: "content/blog",
});
const all = await posts.getAll();
// all[0].metadata is typed as PostFrontmatterIf you pair the generic with frontmatterSchema, the schema is the runtime enforcer and the generic is the static source of truth. They should agree — the package does not infer one from the other.
Nested namespaces
// content/games/{game}/{slug}.mdx
const guides = createMdxCollection({
root: "content/games",
namespaceDepth: 1,
});
const arkGuides = await guides.getAllByNamespace("ark");
const specific = await guides.get({ namespace: "ark", slug: "boss-guide" });Files that sit at the wrong depth throw a clear error — there is no silent coercion.
Schema validation
The schema interface is structural: anything with a parse(input): T method works. No dependency on Zod, Valibot, or Yup.
import { z } from "zod";
const schema = z.object({
title: z.string(),
publishedAt: z.string(),
aliases: z.array(z.string()).optional(),
});
const posts = createMdxCollection({
root: "content/blog",
frontmatterSchema: schema,
});
// In next.config.ts — fail the build if any file drifts:
await posts.validate();Or hand-rolled, no dependencies at all:
const schema = {
parse(input: unknown) {
const obj = input as Record<string, unknown>;
if (typeof obj.title !== "string") throw new Error("title required");
return obj as { title: string };
},
};validate() aggregates every issue and throws MdxValidationError with a structured .issues array, so you can render your own output instead of parsing the message string. getAll() never throws on schema violations — it returns the raw frontmatter, cast to your declared type. Validation is an explicit build-time gate, not a runtime foot-gun.
Catching it in a build script:
import { MdxValidationError } from "@bliztek/mdx-utils/node";
try {
await posts.validate();
} catch (err) {
if (err instanceof MdxValidationError) {
for (const issue of err.issues) {
console.error(`${issue.filePath} · ${issue.path}: ${issue.message}`);
}
process.exit(1);
}
throw err;
}Related entries
Use resolveRelated to turn a slug list on one entry into full entries from the same namespace:
const post = await posts.get({ slug: "boss-guide" });
const related = await posts.resolveRelated(
post?.namespace ?? "",
post?.metadata.relatedSlugs ?? [],
);
// related: MdxEntry[] — unknown slugs skipped with a console.warnRedirects from renamed slugs
// next.config.ts
import { collectRedirects } from "@bliztek/mdx-utils/node";
export default {
async redirects() {
return collectRedirects({
root: "content/games",
namespaceDepth: 1,
basePath: "/games/{namespace}/guides/{slug}",
});
},
};Any entry with an aliases: [...] field in its frontmatter gets one 301 per alias pointing at the current slug. Tokens {namespace} and {slug} are substituted from the entry's real location.
Composing the default frontmatter parser
The built-in parser handles a minimal YAML subset (quoted/unquoted scalars, inline arrays, block arrays). For the long tail, pass a parseFrontmatter override — or compose on top of the default:
import {
createMdxCollection,
defaultParseFrontmatter,
} from "@bliztek/mdx-utils/node";
const posts = createMdxCollection({
root: "content/blog",
parseFrontmatter: (raw) => {
const base = defaultParseFrontmatter(raw);
// coerce numbers, parse dates, etc.
return base;
},
});Or replace it entirely with gray-matter:
import matter from "gray-matter";
createMdxCollection({
root: "content/blog",
parseFrontmatter: (raw) => matter(raw).data,
});Caching
createMdxCollection reads and parses on the first getAll() and caches the result in process. Call collection.invalidate() to force a re-read — useful for dev-mode HMR. Production builds typically call each getter once so caching is a pure win.
Next.js App Router integration
End-to-end wiring for a static blog at app/blog/[slug]/page.tsx:
// lib/posts.ts
import { createMdxCollection } from "@bliztek/mdx-utils/node";
export interface PostFrontmatter {
title: string;
description?: string;
publishedAt: string;
}
export const posts = createMdxCollection<PostFrontmatter>({
root: "content/blog",
});// app/blog/[slug]/page.tsx
import { notFound } from "next/navigation";
import { readMdxFile } from "@bliztek/mdx-utils/node";
import { posts } from "@/lib/posts";
export async function generateStaticParams() {
const all = await posts.getAll();
return all.map((p) => ({ slug: p.slug }));
}
export async function generateMetadata({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const post = await posts.get({ slug });
if (!post) return {};
return {
title: post.metadata.title,
description: post.metadata.description,
};
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const post = await posts.get({ slug });
if (!post) notFound();
const raw = await readMdxFile(post.filePath);
// render `raw` with your MDX compiler of choice — see below
return (
<article>
<h1>{post.metadata.title}</h1>
<p>{post.readTime.minutes} min read</p>
{/* <MDXRemote source={raw} /> */}
</article>
);
}Rendering the MDX
This package deliberately does not compile MDX — that is the job of an MDX compiler, and you should pick the one that fits your runtime. Hand the readMdxFile output to:
- next-mdx-remote — server-component-friendly, works inside App Router
- @mdx-js/mdx — lower-level, use when you want full control over the compile pipeline
- @next/mdx — if you want file-based MDX routing instead of a collection, though this conflicts with
createMdxCollection's indexing model
import { MDXRemote } from "next-mdx-remote/rsc";
const raw = await readMdxFile(post.filePath);
return <MDXRemote source={raw} />;Sitemap
// app/sitemap.ts
import type { MetadataRoute } from "next";
import { posts } from "@/lib/posts";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const all = await posts.getAll();
return all.map((post) => ({
url: `https://example.com/blog/${post.slug}`,
lastModified: post.metadata.publishedAt,
}));
}API
createMdxCollection(options)
| Option | Type | Default | Description |
|---|---|---|---|
| root | string | required | Path to the content root |
| namespaceDepth | number | 0 | Directory segments between root and file to treat as namespace |
| frontmatterSchema | { parse(input): T } | — | Optional structural validator |
| parseFrontmatter | (raw) => object | defaultParseFrontmatter | Frontmatter parser override |
| wordsPerMinute | number | 238 | Override for read-time calculation |
Returns { getAll, getAllByNamespace, get, resolveRelated, validate, invalidate }.
collectRedirects(options)
| Option | Type | Default | Description |
|---|---|---|---|
| root | string | required | Path to the content root |
| namespaceDepth | number | 0 | Same meaning as above |
| basePath | string | required | URL template with {namespace}/{slug} tokens |
| permanent | boolean | true | true → 301, false → 302 |
| aliasField | string | "aliases" | Frontmatter field to read aliases from |
Returns NextRedirect[] — compatible with Next.js redirects() config.
Well-known frontmatter fields
The package treats these fields as well-known when present, but never requires them unless your schema does:
| Field | Type | Purpose |
|---|---|---|
| title | string | Display title |
| description | string | Excerpt / meta description |
| publishedAt | string (ISO) | Used for sort order |
| updatedAt | string (ISO) | For JSON-LD dateModified |
| aliases | string[] | Consumed by collectRedirects |
| relatedSlugs | string[] | Consumed by resolveRelated |
All other fields are passed through untouched.
Types
type TableOfContentsEntry = {
level: number;
text: string;
slug: string;
children?: TableOfContentsEntry[];
};
type TableOfContents = TableOfContentsEntry[];
interface ReadTimeOptions { wordsPerMinute?: number }
interface ReadTimeResult { minutes: number; words: number }
interface GetContentSlugsOptions { extensions?: string[]; recursive?: boolean }
interface FrontmatterSchema<T> { parse(input: unknown): T }Entry Points
| Import | Environment | Contents |
|--------|------------|----------|
| @bliztek/mdx-utils | Any (browser, edge, Node) | calculateReadTime, stripMdxSyntax, sortByDateDescending, types |
| @bliztek/mdx-utils/node | Node.js | createMdxCollection, collectRedirects, defaultParseFrontmatter, MdxValidationError, getContentSlugs, readMdxFile + re-exports from main |
License
MIT
