/

How to Parse Markdown in Next.js

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { useState, useEffect } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { getJob, getJobs } from 'lib/data.js';
import prisma from 'lib/prisma';
import marked from 'marked';
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';

export default function Item({ item }) {
return <p>{item.description}</p>;
}

export async function getStaticPaths() {
const items = await getItems(prisma);

return {
paths: items.map((job) => ({
params: {
id: String(item.id),
},
})),
fallback: false,
};
}

export async function getStaticProps({ params }) {
const id = String(params.id);
const item = await getItem(prisma, id); // unrelated

const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
item.description = DOMPurify.sanitize(marked(item.description));

return { props: { item } };
}

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