How to parse fetched markdown in NextJS with Syntax Highlighting

Thu Feb 11 2021

Instead of writing individual html pages or embedding an article from an external blog site, you may want to make your own customization to your articles and to make use of markdown's simplicity to write blogs alongside NextJS's incremental static site generation for fast loading and dynamic data. However, if you have used a markdown parser, you probably have realized that while it gets the job done, you would prefer to have syntax highlighting in your code snippets rather than just having text that looks somewhat different from your paragraphs. If you have faced this, there is a solution to this. First you need to install two packages: markdown-it and highlight.js.

// if you're using npm

npm i highlight.js
npm i markdown-it

//if you're using yarn

yarn add highlight.js
yarn add markdown-it

First, at the top of your file, you need to import hljs from highlight.js and then import MarkdownIt from markdown-it.

import hljs from 'highlight.js'
import MarkdownIt from 'markdown-it'

After that, you need to create a const (let's call it md) that is equal to a MarkdownIt function that incorporates hljs that was imported. This will allow Markdown-It to recognize parts of your markdown data that has code and will apply syntax highlighting for that language. It should look something like this.

    const md = new MarkdownIt({
        highlight: function (str, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return '<pre class="hljs"><code>' +
                     hljs.highlight(lang, str, true).value +
            } catch (err) {console.log(err)}
          return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';

After that, you can create a div element with an attribute called dangerouslySetInnerHTML. That attribute should contain an object with a propterty called: __html (yes with two underscores). This should be equal to md.render(/your markdown data/, /language/) (assuming that you named the const md). It should look like this:

<div id={} dangerouslySetInnerHTML={{__html: md.render(/*your markdown data*/, */language*/)}}></div>

Finally to make sure that syntax highlighting actually appear, you need to import a css file from highligh.js in your _app.js file. Highlight.js has alot of css styles so you can experiment with those. To find those styles, you can go to the node_modules folder, then inside that folder go to the highlight.js folder, and then styles. The import statement should look something like this:

import 'highlight.js/styles/atelier-forest-light.css'

In the end, you will have a blog article with syntax highlighting. E.G This site