Highlighting markdown using prism in Next.js

There's a lot of option to highlighting code for your next.js application. One of the framework that you can use is Prism. In this tutorial we will try to highlighting markdown file using Remark Prism.

Install Dependencies

Let's start by installing required dependency.

npm install unified remark-parse remark-prism remark-rehype rehype-format rehype-stringify rehype-raw

Yeah that's a lot of dependency, but that's the required dependency to work with remark prism.

Import CSS

Go to pages/_app.js and import the css.

import 'prismjs/themes/prism-okaidia.css';

If you want to use other theme you can use one of this themes.

Compile markdown file

And now you can compile the markdown file to html with syntact highlight.

import unified from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeFormat from 'rehype-format'
import rehypeStringify from 'rehype-stringify'
import remarkPrism from 'remark-prism'
import rehypeRaw from 'rehype-raw'

export function parseMarkdown(content) {
    const processedContent = await unified()
        .use(remarkRehype, { allowDangerousHtml: true })

    return processedContent.toString()

And now you can use it like this.

const md = `
## Title here


const contentHtml = parseMarkdown(md)

And now you can apply to your component.

<div dangerouslySetInnerHTML={{ __html: contentHtml }}></div>

The result will be like this.

Title here


So that's all for this tutorial feel free to reach out via DM in twitter if you can't make it works. Thank you 👋.