How to Parse Markdown in Next.js
If you’re working with Next.js and need to parse Markdown to display it on a page, this guide is for you. In this example, we’ll be using the marked
, dompurify
, and jsdom libraries to accomplish this task.
To begin, let’s assume you have a field containing markdown content that you want to display on a Next.js page. Here’s an example of how you can render an item’s description using these libraries on a Next.js dynamic page.
First, make sure you have the necessary dependencies installed. You can do this using the following command:
1 | npm install marked dompurify jsdom |
Next, let’s take a look at the code in the example Next.js dynamic page:
1 | import { useState, useEffect } from 'react'; |
In this code, we’re using the getStaticProps
function to fetch the item’s data and sanitize the Markdown content. First, we retrieve the item’s description from our data source, and then we create a new window
using JSDOM
from the jsdom
library.
After that, we initialize DOMPurify
using createDOMPurify
and pass it the window
we created earlier. This step is necessary because DOMPurify
assumes a Node.js environment when running server-side. Finally, we use DOMPurify.sanitize
to sanitize the Markdown content and assign the sanitized content back to the item.description
variable.
That’s it! Now you can use the sanitized Markdown content to render it on your page.
Tags: Next.js, Markdown parsing, marked, dompurify, jsdom