Open History to see the last commit
1---
2id: rendering-markdown
3title: Rendering Markdown
4---
5β
6This guide covers two methods for importing and rendering markdown content in your TanStack Start application:
7β
81. **Static markdown** with `content-collections` for build-time loading (e.g., blog posts)
92. **Dynamic markdown** fetched at runtime from GitHub or any remote source
10β
11Both methods share a common rendering pipeline using the `unified` ecosystem.
12β
13## Setting Up the Markdown Processor
14β
15Both approaches use the same markdown-to-HTML processing pipeline. First, install the required dependencies:
16β
17```bash
18npm install unified remark-parse remark-gfm remark-rehype rehype-raw rehype-slug rehype-autolink-headings rehype-stringify shiki html-react-parser gray-matter
19```
20β
21Create a markdown processor utility:
22β
23```tsx
24// src/utils/markdown.ts
25import { unified } from 'unified'
26import remarkParse from 'remark-parse'
27import remarkGfm from 'remark-gfm'
28import remarkRehype from 'remark-rehype'
29import rehypeRaw from 'rehype-raw'
30import rehypeSlug from 'rehype-slug'
31import rehypeAutolinkHeadings from 'rehype-autolink-headings'
32import rehypeStringify from 'rehype-stringify'
33β
34export type MarkdownHeading = {
35 id: string
36 text: string
37 level: number
38}
39β
40export type MarkdownResult = {
41 markup: string
42 headings: Array<MarkdownHeading>
43}
44β
45export async function renderMarkdown(content: string): Promise<MarkdownResult> {
46 const headings: Array<MarkdownHeading> = []
47β
48 const result = await unified()
49 .use(remarkParse) // Parse markdown
50 .use(remarkGfm) // Support GitHub Flavored Markdown
51 .use(remarkRehype, { allowDangerousHtml: true }) // Convert to HTML AST
52 .use(rehypeRaw) // Process raw HTML in markdown
53 .use(rehypeSlug) // Add IDs to headings
54 .use(rehypeAutolinkHeadings, {
55 behavior: 'wrap',
56 properties: { className: ['anchor'] },
57 })
58 .use(() => (tree) => {
59 // Extract headings for table of contents
60 const { visit } = require('unist-util-visit')
61 const { toString } = require('hast-util-to-string')
62β
63 visit(tree, 'element', (node: any) => {
64 if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(node.tagName)) {
65 headings.push({
66 id: node.properties?.id || '',
67 text: toString(node),
68 level: parseInt(node.tagName.charAt(1), 10),
69 })
70 }
71 })
72 })
73 .use(rehypeStringify) // Serialize to HTML string
74 .process(content)
75β
76 return {
77 markup: String(result),
78 headings,
79 }
80}
81```
82β
83## Creating a Markdown Component
84β
85Create a React component that renders the processed HTML with custom element handling:
86β
87```tsx
88// src/components/Markdown.tsx
89import parse, { type HTMLReactParserOptions, Element } from 'html-react-parser'
90import { renderMarkdown, type MarkdownResult } from '~/utils/markdown'
91β
92type MarkdownProps = {
93 content: string
94 className?: string
95}
96β
97export function Markdown({ content, className }: MarkdownProps) {
98 const [result, setResult] = useState<MarkdownResult | null>(null)
99β
100 useEffect(() => {
101 renderMarkdown(content).then(setResult)
102 }, [content])
103β
104 if (!result) {
105 return <div className={className}>Loading...</div>
106 }
107β
108 const options: HTMLReactParserOptions = {
109 replace: (domNode) => {
110 if (domNode instanceof Element) {
111 // Customize rendering of specific elements
112 if (domNode.name === 'a') {
113 // Handle links
114 const href = domNode.attribs.href
115 if (href?.startsWith('/')) {
116 // Internal link - use your router's Link component
117 return (
118 <Link to={href}>{domToReact(domNode.children, options)}</Link>
119 )
120 }
121 }
122β
123 if (domNode.name === 'img') {
124 // Add lazy loading to images
125 return (
126 <img
127 {...domNode.attribs}
128 loading="lazy"
129 className="rounded-lg shadow-md"
130 />
131 )
132 }
133 }
134 },
135 }
136β
137 return <div className={className}>{parse(result.markup, options)}</div>
138}
139```
140β
141## Method 1: Static Markdown with content-collections
142β
143The `content-collections` package is ideal for static content like blog posts that are included in your repository. It processes markdown files at build time and provides type-safe access to the content.
144β
145### Installation
146β
147```bash
148npm install @content-collections/core @content-collections/vite
149```
150β
151### Configuration
152β
153Create a `content-collections.ts` file in your project root:
154β
155```tsx
156// content-collections.ts
157import { defineCollection, defineConfig } from '@content-collections/core'
158import matter from 'gray-matter'
159β
160function extractFrontMatter(content: string) {
161 const { data, content: body, excerpt } = matter(content, { excerpt: true })
162 return { data, body, excerpt: excerpt || '' }
163}
164β
165const posts = defineCollection({
166 name: 'posts',
167 directory: './src/blog', // Directory containing your .md files
168 include: '*.md',
169 schema: (z) => ({
170 title: z.string(),
171 published: z.string().date(),
172 description: z.string().optional(),
173 authors: z.string().array(),
174 }),
175 transform: ({ content, ...post }) => {
176 const frontMatter = extractFrontMatter(content)
177β
178 // Extract header image (first image in the document)
179 const headerImageMatch = content.match(/!\[([^\]]*)\]\(([^)]+)\)/)
180 const headerImage = headerImageMatch ? headerImageMatch[2] : undefined
181β
182 return {
183 ...post,
184 slug: post._meta.path,
185 excerpt: frontMatter.excerpt,
186 description: frontMatter.data.description,
187 headerImage,
188 content: frontMatter.body,
189 }
190 },
191})
192β
193export default defineConfig({
194 collections: [posts],
195})
196```
197β
198### Vite Integration
199β
200Add the content-collections plugin to your Vite config:
201β
202```tsx
203// app.config.ts
204import { defineConfig } from '@tanstack/react-start/config'
205import contentCollections from '@content-collections/vite'
206β
207export default defineConfig({
208 vite: {
209 plugins: [contentCollections()],
210 },
211})
212```
213β
214### Creating Blog Posts
215β
216Create markdown files in your designated directory:
217β
218````markdown
219## <!-- src/blog/hello-world.md -->
220β
221title: Hello World
222published: 2024-01-15
223authors:
224β
225- Jane Doe
226 description: My first blog post
227β
228---
229β
230
231β
232Welcome to my blog! This is my first post.
233β
234## Getting Started
235β
236Here's some content with **bold** and _italic_ text.
237β
238```javascript
239console.log('Hello, world!')
240```
241````
242β
243### Using the Collection
244β
245Access your posts through the generated collection:
246β
247```tsx
248// src/routes/blog.index.tsx
249import { createFileRoute } from '@tanstack/react-router'
250import { allPosts } from 'content-collections'
251β
252export const Route = createFileRoute('/blog/')({
253 component: BlogIndex,
254})
255β
256function BlogIndex() {
257 // Posts are sorted by published date
258 const sortedPosts = allPosts.sort(
259 (a, b) => new Date(b.published).getTime() - new Date(a.published).getTime(),
260 )
261β
262 return (
263 <div>
264 <h1>Blog</h1>
265 <ul>
266 {sortedPosts.map((post) => (
267 <li key={post.slug}>
268 <Link to="/blog/$slug" params={{ slug: post.slug }}>
269 <h2>{post.title}</h2>
270 <p>{post.excerpt}</p>
271 <span>{post.published}</span>
272 </Link>
273 </li>
274 ))}
275 </ul>
276 </div>
277 )
278}
279```
280β
281### Rendering a Single Post
282β
283```tsx
284// src/routes/blog.$slug.tsx
285import { createFileRoute, notFound } from '@tanstack/react-router'
286import { allPosts } from 'content-collections'
287import { Markdown } from '~/components/Markdown'
288β
289export const Route = createFileRoute('/blog/$slug')({
290 loader: ({ params }) => {
291 const post = allPosts.find((p) => p.slug === params.slug)
292 if (!post) {
293 throw notFound()
294 }
295 return post
296 },
297 component: BlogPost,
298})
299β
300function BlogPost() {
301 const post = Route.useLoaderData()
302β
303 return (
304 <article>
305 <header>
306 <h1>{post.title}</h1>
307 <p>
308 By {post.authors.join(', ')} on {post.published}
309 </p>
310 </header>
311 <Markdown content={post.content} className="prose" />
312 </article>
313 )
314}
315```
316β
317## Method 2: Dynamic Markdown from Remote Sources
318β
319For content stored externally (like GitHub repositories), you can fetch and render markdown dynamically using server functions.
320β
321### Creating a Fetch Utility
322β
323```tsx
324// src/utils/docs.server.ts
325import { createServerFn } from '@tanstack/react-start'
326import matter from 'gray-matter'
327β
328type FetchDocsParams = {
329 repo: string // e.g., 'tanstack/router'
330 branch: string // e.g., 'main'
331 filePath: string // e.g., 'docs/guide/getting-started.md'
332}
333β
334export const fetchDocs = createServerFn({ method: 'GET' })
335 .validator((params: FetchDocsParams) => params)
336 .handler(async ({ data: { repo, branch, filePath } }) => {
337 const url = `https://raw.githubusercontent.com/${repo}/${branch}/${filePath}`
338β
339 const response = await fetch(url, {
340 headers: {
341 // Add GitHub token for private repos or higher rate limits
342 // Authorization: `token ${process.env.GITHUB_TOKEN}`,
343 },
344 })
345β
346 if (!response.ok) {
347 throw new Error(`Failed to fetch: ${response.status}`)
348 }
349β
350 const rawContent = await response.text()
351 const { data: frontmatter, content } = matter(rawContent)
352β
353 return {
354 frontmatter,
355 content,
356 filePath,
357 }
358 })
359```
360β
361### Adding Cache Headers
362β
363For production, add appropriate cache headers:
364β
365```tsx
366export const fetchDocs = createServerFn({ method: 'GET' })
367 .validator((params: FetchDocsParams) => params)
368 .handler(async ({ data: { repo, branch, filePath }, context }) => {
369 // Set cache headers for CDN caching
370 context.response.headers.set(
371 'Cache-Control',
372 'public, max-age=0, must-revalidate',
373 )
374 context.response.headers.set(
375 'CDN-Cache-Control',
376 'max-age=300, stale-while-revalidate=300',
377 )
378β
379 // ... fetch logic
380 })
381```
382β
383### Using Dynamic Markdown in Routes
384β
385```tsx
386// src/routes/docs.$path.tsx
387import { createFileRoute } from '@tanstack/react-router'
388import { fetchDocs } from '~/utils/docs.server'
389import { Markdown } from '~/components/Markdown'
390β
391export const Route = createFileRoute('/docs/$path')({
392 loader: async ({ params }) => {
393 return fetchDocs({
394 data: {
395 repo: 'your-org/your-repo',
396 branch: 'main',
397 filePath: `docs/${params.path}.md`,
398 },
399 })
400 },
401 component: DocsPage,
402})
403β
404function DocsPage() {
405 const { frontmatter, content } = Route.useLoaderData()
406β
407 return (
408 <article>
409 <h1>{frontmatter.title}</h1>
410 <Markdown content={content} className="prose" />
411 </article>
412 )
413}
414```
415β
416### Fetching Directory Contents
417β
418To build navigation from a GitHub directory:
419β
420```tsx
421// src/utils/docs.server.ts
422type GitHubContent = {
423 name: string
424 path: string
425 type: 'file' | 'dir'
426}
427β
428export const fetchRepoContents = createServerFn({ method: 'GET' })
429 .validator((params: { repo: string; branch: string; path: string }) => params)
430 .handler(async ({ data: { repo, branch, path } }) => {
431 const url = `https://api.github.com/repos/${repo}/contents/${path}?ref=${branch}`
432β
433 const response = await fetch(url, {
434 headers: {
435 Accept: 'application/vnd.github.v3+json',
436 // Authorization: `token ${process.env.GITHUB_TOKEN}`,
437 },
438 })
439β
440 if (!response.ok) {
441 throw new Error(`Failed to fetch contents: ${response.status}`)
442 }
443β
444 const contents: Array<GitHubContent> = await response.json()
445β
446 return contents
447 .filter((item) => item.type === 'file' && item.name.endsWith('.md'))
448 .map((item) => ({
449 name: item.name.replace('.md', ''),
450 path: item.path,
451 }))
452 })
453```
454β
455## Adding Syntax Highlighting with Shiki
456β
457For code blocks with syntax highlighting, integrate Shiki into your markdown processor:
458β
459```tsx
460// src/utils/markdown.ts
461import { codeToHtml } from 'shiki'
462β
463// Process code blocks after parsing
464export async function highlightCode(
465 code: string,
466 language: string,
467): Promise<string> {
468 return codeToHtml(code, {
469 lang: language,
470 themes: {
471 light: 'github-light',
472 dark: 'tokyo-night',
473 },
474 })
475}
476```
477β
478Then handle code blocks in your Markdown component:
479β
480```tsx
481// In your Markdown component's replace function
482if (domNode.name === 'pre') {
483 const codeElement = domNode.children.find(
484 (child) => child instanceof Element && child.name === 'code',
485 )
486 if (codeElement) {
487 const className = codeElement.attribs.class || ''
488 const language = className.replace('language-', '') || 'text'
489 const code = getText(codeElement)
490β
491 return <CodeBlock code={code} language={language} />
492 }
493}
494```
495β
496## Summary
497β
498| Approach | Best For | Pros | Cons |
499| ------------------- | ----------------------------------------- | ---------------------------------------------- | ----------------------------------------- |
500| content-collections | Blog posts, static docs bundled with app | Type-safe, build-time processing, fast runtime | Requires rebuild for content updates |
501| Dynamic fetching | External docs, frequently updated content | Always fresh, no rebuild needed | Runtime overhead, requires error handling |
502β
503Choose the approach that best fits your content update frequency and deployment workflow. For hybrid scenarios, you can use both methods in the same application.