Dan Stroot

Adding Syntax Highlighting in Nextjs

If you want to show example code on a page in Nextjs you will help your readers by implemeting some form of syntax highlighting. Here's how.

Date:


Adding highlighting in a markdown-based blog

1

Add syntax highlights to markdown code

If you are using something like Remark you can simply add remark-prism to your markdown processing as follows.

markdownToHTML.js
(javascript)
import { remark } from 'remark'
import emoji from 'remark-emoji'
import gfm from 'remark-gfm'
import html from 'remark-html'
import prism from 'remark-prism'
 
/*
Using remark to convert markdown to HTML:
  - prism for code syntax highlighting
  - gfm for tables
  - emoji
*/
 
export async function markdownToHTML(markdown) {
  const result = await remark()
    .use(html, { sanitize: false })
    .use(gfm)
    .use(prism)
    .use(emoji)
    .process(markdown)
  return result.toString()
}
2

Add css

Then, make sure you load a prism css theme to actually colorize your code.

/pages/_app.js
(javascript)
import 'prismjs/themes/prism-tomorrow.css'
import '../styles/index.css'
 
export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

Adding highlighting to HTML directly

In this case we will be moving some of the work from the server to the client

1

Install prism js using npm / yarn

(sh)
npm i prismjs
yarn add prismjs

Prismjs also provides TypeScript support, npm i @types/prismjs or yarn add @types/prismjs

1

Use prismjs on your page

Import prismjs into your blog page and highlight all. The next step is just import prismjs into your codes and call the highlightAll function in your useEffect / componentDidMount.

/pages/page.js
(javascript)
import Prism from 'prismjs';
import "prismjs/components/prism-java"; // if you need a specific language
import 'prismjs/themes/prism-tomorrow.css'; // css theme
 
export default function Index() {
 
  useEffect(() => {
    if (typeof window !== 'undefined') { // don't run on server
        Prism.highlightAll();
    }
  }, []);
 
  return (
    <pre class="language-javascript" >
      <code>
        function getFullName (user) {
          const fullName = user.firstName + user.lastName;
 
          return fullName;
        }
      </code>
    </pre>
  );
}

It will automatically select the code blocks and will highlight them all. Note, you must have your code in the format above.

References

Sharing is Caring

Edit this page