Open History to see the last commit
1---
2id: rendering-markdown
3title: Rendering Markdown
4---
5β
6Use [TanStack Markdown](https://tanstack.com/markdown/latest/docs/overview) to render Markdown in your TanStack Start application. Its React renderer works synchronously during server rendering and client navigation, so content does not need to wait for a client effect.
7β
8This guide covers static posts loaded with Content Collections and remote content fetched through a server function. Both use the same Markdown component.
9β
10## Rendering Markdown
11β
12Install TanStack Markdown:
13β
14```bash
15npm install @tanstack/markdown
16```
17β
18Create a shared component that accepts either Markdown source or a parsed document:
19β
20```tsx
21// src/components/Markdown.tsx
22import { Markdown as ReactMarkdown } from '@tanstack/markdown/react'
23import type { MarkdownDocument } from '@tanstack/markdown'
24β
25type MarkdownProps = {
26 content: string | MarkdownDocument
27 className?: string
28}
29β
30export function Markdown({ content, className }: MarkdownProps) {
31 return (
32 <div className={className}>
33 <ReactMarkdown headingAnchors>{content}</ReactMarkdown>
34 </div>
35 )
36}
37```
38β
39Headings receive stable IDs, and `headingAnchors` adds links to them. Raw HTML is escaped and unsafe URL protocols are removed by default. Keep these defaults for remote or user-written content. TanStack Markdown does not execute MDX or implement every CommonMark or GFM feature, so check the [supported syntax](https://tanstack.com/markdown/latest/docs/core-concepts/syntax-profile) when migrating existing content.
40β
41Use the `components` prop to customize elements, for example to lazy-load images:
42β
43```tsx
44<ReactMarkdown
45 components={{
46 img: (props) => <img {...props} loading="lazy" />,
47 }}
48>
49 {content}
50</ReactMarkdown>
51```
52β
53The examples below use `~/*` for the `src/*` import alias. The `prose` class is optional and requires your own typography styles, such as Tailwind Typography.
54β
55## Static Markdown with Content Collections
56β
57[Content Collections](https://www.content-collections.dev/docs/quickstart/tanstack-start) loads local Markdown files and validates their frontmatter. Pass the Markdown body from the generated collection to the shared renderer.
58β
59### Installation and Configuration
60β
61```bash
62npm install -D @content-collections/core @content-collections/vite zod
63```
64β
65```ts
66// content-collections.ts
67import { defineCollection, defineConfig } from '@content-collections/core'
68import { z } from 'zod'
69β
70const posts = defineCollection({
71 name: 'posts',
72 directory: './src/blog',
73 include: '*.md',
74 schema: z.object({
75 title: z.string(),
76 published: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
77 description: z.string(),
78 authors: z.array(z.string()),
79 content: z.string(),
80 }),
81 transform: (post) => ({
82 ...post,
83 slug: post._meta.path,
84 }),
85})
86β
87export default defineConfig({
88 collections: [posts],
89})
90```
91β
92Content Collections already separates frontmatter from `content`, so this transform does not need a second frontmatter parser.
93β
94Add the plugin to your existing Vite configuration, keeping any deployment plugins your app needs:
95β
96```ts
97// vite.config.ts
98import contentCollections from '@content-collections/vite'
99import { tanstackStart } from '@tanstack/react-start/plugin/vite'
100import viteReact from '@vitejs/plugin-react'
101import { defineConfig } from 'vite'
102import tsConfigPaths from 'vite-tsconfig-paths'
103β
104export default defineConfig({
105 plugins: [
106 contentCollections(),
107 tsConfigPaths({ projects: ['./tsconfig.json'] }),
108 tanstackStart(),
109 viteReact(),
110 ],
111})
112```
113β
114Add the generated collection alias to your existing `tsconfig.json`:
115β
116```json
117{
118 "compilerOptions": {
119 "paths": {
120 "~/*": ["./src/*"],
121 "content-collections": ["./.content-collections/generated"]
122 }
123 }
124}
125```
126β
127Add `.content-collections` to `.gitignore`. Starting the Vite dev server or running a build generates the collection.
128β
129### Creating a Post
130β
131Create `src/blog/hello-world.md`:
132β
133````markdown
134---
135title: Hello World
136published: '2026-01-15'
137description: My first blog post
138authors:
139 - Jane Doe
140---
141β
142Welcome to my blog! This is my first post.
143β
144## Getting Started
145β
146Here's some content with **bold** and _italic_ text.
147β
148```javascript
149console.log('Hello, world!')
150```
151````
152β
153### Listing Posts
154β
155```tsx
156// src/routes/blog.index.tsx
157import { createFileRoute, Link } from '@tanstack/react-router'
158import { allPosts } from 'content-collections'
159β
160export const Route = createFileRoute('/blog/')({
161 component: BlogIndex,
162})
163β
164function BlogIndex() {
165 const sortedPosts = [...allPosts].sort((a, b) =>
166 b.published.localeCompare(a.published),
167 )
168β
169 return (
170 <main>
171 <h1>Blog</h1>
172 <ul>
173 {sortedPosts.map((post) => (
174 <li key={post.slug}>
175 <Link to="/blog/$slug" params={{ slug: post.slug }}>
176 {post.title}
177 </Link>
178 <p>{post.description}</p>
179 <time dateTime={post.published}>{post.published}</time>
180 </li>
181 ))}
182 </ul>
183 </main>
184 )
185}
186```
187β
188### Rendering a Post
189β
190```tsx
191// src/routes/blog.$slug.tsx
192import { createFileRoute, notFound } from '@tanstack/react-router'
193import { allPosts } from 'content-collections'
194import { Markdown } from '~/components/Markdown'
195β
196export const Route = createFileRoute('/blog/$slug')({
197 loader: ({ params }) => {
198 const post = allPosts.find((post) => post.slug === params.slug)
199 if (!post) {
200 throw notFound()
201 }
202 return post
203 },
204 component: BlogPost,
205})
206β
207function BlogPost() {
208 const post = Route.useLoaderData()
209β
210 return (
211 <article>
212 <h1>{post.title}</h1>
213 <p>
214 By {post.authors.join(', ')} on {post.published}
215 </p>
216 <Markdown content={post.content} className="prose" />
217 </article>
218 )
219}
220```
221β
222The renderer parses the Markdown synchronously and renders React elements on both the server and client.
223β
224## Remote Markdown with a Server Function
225β
226Fetch remote content in a server function and parse it before returning it to the route. Install `gray-matter` if the remote files contain frontmatter:
227β
228```bash
229npm install gray-matter
230```
231β
232Keep the repository, branch, and content directory in server code. Validate the requested filename before building the URL:
233β
234```ts
235// src/utils/docs.ts
236import { createServerFn } from '@tanstack/react-start'
237import { notFound } from '@tanstack/react-router'
238import { parseMarkdown } from '@tanstack/markdown/parser'
239import matter from 'gray-matter'
240β
241export const fetchDocs = createServerFn({ method: 'GET' })
242 .validator((slug: unknown) => {
243 if (typeof slug !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) {
244 throw new Error('Invalid document slug')
245 }
246 return slug
247 })
248 .handler(async ({ data: slug }) => {
249 // Replace this with your public repository's content directory.
250 const baseUrl =
251 'https://raw.githubusercontent.com/your-org/your-repo/main/docs'
252 const response = await fetch(`${baseUrl}/${slug}.md`)
253β
254 if (response.status === 404) {
255 throw notFound()
256 }
257 if (!response.ok) {
258 throw new Error(`Failed to fetch document: ${response.status}`)
259 }
260β
261 const { data, content } = matter(await response.text())
262β
263 return {
264 title: typeof data.title === 'string' ? data.title : slug,
265 document: parseMarkdown(content),
266 }
267 })
268```
269β
270```tsx
271// src/routes/docs.$slug.tsx
272import { createFileRoute } from '@tanstack/react-router'
273import { Markdown } from '~/components/Markdown'
274import { fetchDocs } from '~/utils/docs'
275β
276export const Route = createFileRoute('/docs/$slug')({
277 loader: ({ params }) => fetchDocs({ data: params.slug }),
278 component: DocsPage,
279})
280β
281function DocsPage() {
282 const { title, document } = Route.useLoaderData()
283β
284 return (
285 <article>
286 <h1>{title}</h1>
287 <Markdown content={document} className="prose" />
288 </article>
289 )
290}
291```
292β
293Relative Markdown links and image URLs resolve against your app's URL, not the source repository. Use app-relative or absolute URLs in the content, or transform them for your site's route and asset layout.
294β
295## Syntax Highlighting with TanStack Highlight
296β
297Install [TanStack Highlight](https://tanstack.com/highlight/latest/docs/overview). The Markdown adapter requires version `0.0.6` or newer:
298β
299```bash
300npm install @tanstack/highlight
301```
302β
303Register the languages your content uses and create the Markdown adapter:
304β
305```ts
306// src/utils/markdown-highlighter.ts
307import { createHighlighter } from '@tanstack/highlight/core'
308import { js } from '@tanstack/highlight/languages/js'
309import { plaintext } from '@tanstack/highlight/languages/plaintext'
310import { ts } from '@tanstack/highlight/languages/ts'
311import { tsx } from '@tanstack/highlight/languages/tsx'
312import { createTanStackMarkdownHighlighter } from '@tanstack/highlight/markdown'
313β
314const highlighter = createHighlighter({
315 languages: [plaintext, js, ts, tsx],
316})
317β
318export const highlightMarkdownCode =
319 createTanStackMarkdownHighlighter(highlighter)
320```
321β
322Update the shared component to pass the highlighter and include its theme styles:
323β
324```tsx
325// src/components/Markdown.tsx
326import { createThemeCss } from '@tanstack/highlight/theme'
327import { githubDarkTheme } from '@tanstack/highlight/themes/github-dark'
328import { githubLightTheme } from '@tanstack/highlight/themes/github-light'
329import { Markdown as ReactMarkdown } from '@tanstack/markdown/react'
330import type { MarkdownDocument } from '@tanstack/markdown'
331import { highlightMarkdownCode } from '~/utils/markdown-highlighter'
332β
333const themeCss = createThemeCss({
334 light: githubLightTheme,
335 dark: githubDarkTheme,
336 lightSelector: '.markdown-renderer',
337 darkSelector: '.dark .markdown-renderer',
338 codeBlockSelector: '.markdown-renderer pre.tm-code',
339 lineNumbersSelector: '.markdown-renderer .tm-code--line-numbers',
340})
341β
342type MarkdownProps = {
343 content: string | MarkdownDocument
344 className?: string
345}
346β
347export function Markdown({ content, className }: MarkdownProps) {
348 return (
349 <div className={`markdown-renderer ${className ?? ''}`}>
350 <style>{themeCss}</style>
351 <ReactMarkdown headingAnchors highlighter={highlightMarkdownCode}>
352 {content}
353 </ReactMarkdown>
354 </div>
355 )
356}
357```
358β
359The adapter returns escaped token markup inside the renderer's own `<pre><code>` elements. Unknown languages fall back to plain text. Add a `dark` class to an ancestor to select the dark theme. See the [syntax highlighting guide](https://tanstack.com/markdown/latest/docs/guides/syntax-highlighting) for line numbers and highlighted lines.
360β
361## Table of Contents
362β
363To collect headings, add the docs preset when parsing the document:
364β
365```ts
366import { docsMarkdownExtensions } from '@tanstack/markdown/extensions/docs'
367import { parseMarkdown } from '@tanstack/markdown/parser'
368β
369const document = parseMarkdown(content, {
370 extensions: docsMarkdownExtensions(),
371})
372β
373const headings = document.headings ?? []
374// Each heading has an id, text, and level.
375```
376β
377Use this in the server function, then render links to each heading's `id`. The [docs preset guide](https://tanstack.com/markdown/latest/docs/guides/docs-preset) also covers callouts and custom comment components. Those features need the same extensions passed to the renderer.