Highlight.js provides a lot of helpful documentation, however, it is primarily focused on the client-side implementation. There are other articles out there that explain how to do client-side rendering with Highlight.js and Next.js specifically, but we did not find any that demonstrated a good server-side implementation, so we set out to figure it out for ourselves, and we'd like to share our implementation with the world.
Installing and Importing Highlight.js
Creating the React Component
Now let’s create a React component that renders our code, but before we do, take note that we’re using the dangerouslySetInnerHTML attribute, so named because you should think hard about what kind of content you’re passing to it. It is safe to use static content, which is what we’re doing here.
The hljs.highlight() method generates an HTML string. This differs from the more common implementation where you might see the hljs.highlightAll() method called, which scans the page on the client side and updates it with syntax highlighting. Since hljs.highlightAll() runs client-side, it can unintentionally spill out into other parts of your page and apply highlighting where you don't want it. Using hljs.highlight() and then setting the HTML ourselves ensures that the highlighting is confined to our one component.
Bonus: Super Simple JSON Highlighting
We hope you find this tutorial helpful! At Nextform, we love software that makes our lives easier. That's why we created an API that helps businesses collect and track standard forms like W-9 and W-8BEN. This is a great service for SaaS businesses that need to collect these forms as part of a streamlined onboarding process. If that's you, sign up for a free trial and don't hesitate to contact us with any questions or feature requests.