Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

rendering-markdown.md

377 lines10.9 KB

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
29​
30export function Markdown({ content, className }: MarkdownProps) {
31 return (
32 <div className={className}>
33 <ReactMarkdown headingAnchors>{content}</ReactMarkdown>
34 </div>
35 )
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 }}
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
118 "compilerOptions": {
119 "paths": {
120 "~/*": ["./src/*"],
121 "content-collections": ["./.content-collections/generated"]
122 }
123 }
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 )
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 )
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 )
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
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 )
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.