Markdown is close to plain text, easy to learn, and structured enough to be parsed and converted into whatever output you need. The trade-off is that parsing, processing and converting it takes code, and shipping that code to the browser costs a few dozen kilobytes that exist only to deal with Markdown.
A Next.js application can keep all of that on the server side by relying on the Unified/Remark ecosystem.
Keeping Markdown on the server
The approach is to handle Markdown exclusively inside getStaticProps, so it runs at build time (or in a Next serverless function when using Vercel's incremental builds) and never in the client. getServerSideProps would also work, though getStaticProps is probably the more common case.
getStaticProps returns an AST — an Abstract Syntax Tree, a large nested object describing the content — produced by parsing and processing the Markdown. The client then has the sole job of rendering that tree into React components.
Rendering Markdown straight to HTML inside getStaticProps and passing it to dangerouslySetInnerHtml is another possibility, but it is not recommended: security matters, and rendering through your own components is more flexible than emitting plain HTML.
export const getStaticProps = async () => {
// Get the Markdown content from somewhere, like a CMS or whatnot. It doesn’t
// matter for the sake of this article, really. It could also be read from a
// file.
const markdown = await getMarkdownContentFromSomewhere()
const ast = parseMarkdown(markdown)
return { props: { ast } }
}
const Page = props => {
// This would usually have your layout and whatnot as well, but omitted here
// for sake of simplicity of course.
return <MarkdownRenderer ast={props.ast} />
}
export default Page
Parsing and processing
Install unified and remark-parse. Parsing the Markdown string is then straightforward.
import { unified } from 'unified'
import markdown from 'remark-parse'
const parseMarkdown = content => unified().use(markdown).parse(content)
export default parseMarkdown
A common frustration is that plugins such as remark-prism or remark-slug appear to do nothing. The reason is that Unified's .parse(..) method only turns the Markdown string into a tree; it does not apply plugins to the AST.
Plugins are applied during what Unified calls the "run" phase, which is normally reached through .process(..). But .process(..) parses and runs the plugins and then also stringifies the AST into another format — HTML via remark-html, JSX via remark-react — and that last step is exactly what we want to avoid, since the point is to keep the processed tree intact.
| ........................ process ........................... |
| .......... parse ... | ... run ... | ... stringify ..........|
+--------+ +----------+
Input ->- | Parser | ->- Syntax Tree ->- | Compiler | ->- Output
+--------+ | +----------+
X
|
+--------------+
| Transformers |
+--------------+
Unified has no method for two of the three phases, but it exposes each phase individually, so they can be chained manually:
import { unified } from 'unified'
import markdown from 'remark-parse'
import prism from 'remark-prism'
const parseMarkdown = content => {
const engine = unified().use(markdown).use(prism)
const ast = engine.parse(content)
// Unified‘s *process* contains 3 distinct phases: parsing, running and
// stringifying. We do not want to go through the stringifying phase, since we
// want to preserve an AST, so we cannot call `.process(..)`. Calling
// `.parse(..)` is not enough though as plugins (so Prism) are executed during
// the running phase. So we need to manually call the run phase (synchronously
// for simplicity).
// See: https://github.com/unifiedjs/unified#description
return engine.runSync(ast)
}
That parses the Markdown and runs the plugins on the resulting tree, synchronously here for simplicity, though .run(..) can be used for the asynchronous variant. The tree is never stringified; that happens during rendering instead.
Rendering the tree
A MarkdownRenderer component takes the tree as an ast prop and renders it with React components.
const getComponent = node => {
switch (node.type) {
case 'root':
return ({ children }) => <>{children}</>
case 'paragraph':
return ({ children }) => <p>{children}</p>
case 'emphasis':
return ({ children }) => <em>{children}</em>
case 'heading':
return ({ children, depth = 2 }) => {
const Heading = `h${depth}`
return <Heading>{children}</Heading>
}
case 'text':
return ({ value }) => <>{value}</>
/* Handle all types here … */
default:
console.log('Unhandled node type', node)
return ({ children }) => <>{children}</>
}
}
const Node = node => {
const Component = getComponent(node)
const { children } = node
return children ? (
<Component {...node}>
{children.map((child, index) => (
<Node key={index} {...child} />
))}
</Component>
) : (
<Component {...node} />
)
}
const MarkdownRenderer = props => <Node {...props.ast} />
export default React.memo(MarkdownRenderer)
Most of the logic sits in the Node component. It decides what to render from the node's type key — a getComponent method handles every node type — and then renders it. Nodes with children are rendered recursively; nodes without them are rendered as final leaves.
Cleaning up the serialized tree
Certain Remark plugins produce an AST that Next.js refuses to serialize:
Error: Error serializing
.content[0].content.children[3].data.hChildren[0].data.hChildren[0].data.hChildren[0].data.hChildren[0].data.hNamereturned fromgetStaticPropsin “/”. Reason:undefinedcannot be serialized as JSON. Please usenullor omit this value.
Some keys hold undefined, which cannot be serialized as JSON. Next.js offers two fixes: omit the value, or replace it with null if it needs to stay. Fixing every path by hand is impractical, so the AST is walked recursively and cleaned before it is returned. The culprit in this case was remark-prism, which adds a [data] object to nodes.
const cleanNode = node => {
if (node.value === undefined) delete node.value
if (node.tagName === undefined) delete node.tagName
if (node.data) {
delete node.data.hName
delete node.data.hChildren
delete node.data.hProperties
}
if (node.children) node.children.forEach(cleanNode)
return node
}
const parseMarkdown = content => {
const engine = unified().use(markdown).use(prism)
const ast = engine.parse(content)
const processedAst = engine.runSync(parsed)
cleanNode(processedAst)
return processedAst
}
A further reduction in payload comes from removing the position object that every node carries to record its location in the original Markdown string. It holds only two keys, but across a large tree it adds up quickly.
const cleanNode = node => {
delete node.position
Result
Markdown handling stays confined to build- and server-side code, so no Markdown runtime is shipped to the browser. What crosses to the client is a tree of data that can be walked and mapped onto any React components you choose.



