Syntax highlighting with Prism and Next.js

Syntax highlighting with Prism and Next.js

So you to build a Nextjs blog. As a Dev Blogger, you need code snippets that have syntax highlighting and are easy to read.

This blog post shows you the steps to setting it up.

Syntax highlighting is a great way to make code more readable; in this tutorial, I will show you how you can use PrismJs with Next.js to highlight the code blocks and code snippets inside your blog posts.

Why PrismJs?

PrismJS is the ideal choice for highlight syntax with JavaScript right in the browser. PrismJS has support for all modern browsers. It has +5M downloads per week from npmjs.com. PrismJs is a lightweight, fast code highlighting library explicitly made for frontend languages.

It depends on community contributions to expand and cover all languages. The highlighting is very customizable and has a variety of languages and themes. PrismJs It has been designed to be highly customizable with the most beautiful shade of colors, and you can also extend it. And it supports almost every Programming language.

If you want to use a library in your frontend, it is a must for the library to be lightweight because it will run on the client-side (on the user's browser). This means we must use lightweight packages in our frontend of the application.


Using PrismJs with Next.js

PrismJs is a syntax highlighting library. It is designed to use as little of your computer's resources as possible and can be customized with CSS and JavaScript.

This article will show you how to set up PrismJs with Next.js and create a simple syntax highlighter for your blog posts.

How it works?

Let's see how highlighting code works in the first place, suppose you are building a personal blog and want to create blog posts, you have two options to save your blog data inside your database, one of them is to save your blog content as pure HTML and then return the HTML later when a user shows the page.

The better way to do this is using the Markdown language.

Markdown is a lightweight markup language with plain text formatting syntax. It is designed to be easy to read and write for people who are not experts in the computer programming language.

The goal of Markdown is to be as easy-to-read and easy to write as possible. A markdown-formatted document should be publishable as-is, as plain text, without looking like it's been marked up with tags or formatting instructions, if you don't know how the Markdown works, please make sure you read it here.

SEO tactics

The goal is to get the Markdown from the database and show it on our HTML page, but we can not directly do that because if we do, the reader will see the Markdown code, which is not something you'd want to happen.

For that, we will use a library called React Markdown which is a library that converts Markdown to React components (JSX) which is precisely what we need.

This will convert your Markdown syntax to HTML syntax. For example, it converts (# to h1, and ## to h2, etc.), which means now we have pure HTML syntax in our HTML page, which is exactly what we need.

React Markdown automatically puts any Markdown syntax code blocks inside the <pre> tag and then inside the <code> tag, for example:

<pre>
  <code>Your code here</code>
</pre>

Starting a Next.js app

We first initialize a Next.js application with npx create-next-app@latest prism-app. We will put this in a named folder, in this case (prism-app)

Installing dependencies

There are some dependencies that we will need in order to set up our syntax highlighting, this will install all of the dependencies required to pick up that syntax from the text content and change the colors according to it is syntax.

This library does not include the CSS files, the CSS files need to be downloaded into the project separately which we will cover later.

npm Install prismjs yarn add prism yarn add prismjsInstall react-markdown

Starting with React Markdown

With React markdown, we will parse our Markdown and convert them to HTML tags. Here is how:

export default function app({ markdownContent }) {
  return (
    <div className="container">
      <ReactMarkdown children={markdownContent} />
    </div>
  )
}

As simple as that, React Markdown will handle all of the Markdown converting with the highest level of safety, which means you are safe from XSS Attacks that users might want to utilize.

An XSS attack is a type of attack that allows an attacker to inject malicious code into a web page. This malicious code can then be executed by unsuspecting users who visit the page, XSS attacks can be used to steal sensitive information, hijack user sessions, or redirect users to malicious websites, as a result, it is important for businesses to ensure that their web applications are properly designed and implemented in order to protect against XSS attacks.

React Markdown will automatically purify any malicious code that is in the text content and will not treat it as actual code but as regular text.

Prism Themes

There are various Prism themes that you can apply to your code. Here is how you can use them, go to the PrismJS GitHub repository. There are a bunch of themes that you can choose; pick the one you like, download the CSS file, and then import it to your _app.js file.

import "../styles/globals.css"

import "../styles/prism-one-dark.css"

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

PrismJs theme examples

code block, css class, const codecode block prism, code highlight, syntax code using prismown custom theme, js theme, code editor

SEO tactics

Highlighting code blocks with PrismJS

Now that we have the code blocks in our HTML pages and the Prism CSS file, it is time to highlight the syntax to make it more readable and beautiful to the reader, since we are using Next.js, we will use the React hook useEffect, and we will run a function when the React component mounts, highlighting all the syntax.

First, we import prism, and the function that we are planning to run is highlightAll() comes with Prismjs, which will automatically grab the <pre> and <code> blocks and will highlight them all.

We also have to import JavaScript for each programming language so that PrismJS can highlight a specific programming language. You can import only the programming language that you want to import as few resources as possible, which will make your front end blazing fast without the user having to download large chunks of JavaScript.

Your js file should look something like this:

import { useEffect } from "react"

import Prism from "prismjs"

require("prismjs/components/prism-javascript")

require("prismjs/components/prism-css")

require("prismjs/components/prism-jsx")

export default function app({ markdownContent }) {
  useEffect(() => {
    Prism.highlightAll()
  }, [])

  return (
    <div className="container">
      <ReactMarkdown children={markdownContent} />
    </div>
  )
}

That's it; now your syntax highlighter must work perfectly; feel free to try the other Prism themes and see which one you like the most, if you liked this article, please make sure you follow me on Twitter, where I write daily tweets about web development.

Comments

We won't show your email address!

500 characters left

vitoz

Hi thank u

React and express.js form validations with Zod

Simplified form validations tutorial for frontend (React) and backend (express.js)

React and express.js form validations with Zod

Building a REST API with Prisma and express.js

Prisma is an amazing tool when it comes to TypeScript ORMs, in this tutorial we are going to build a REST API with Prisma and Express.js.

Building a REST API with Prisma and express.js

10 React community hooks you should be using

When it comes to programming, clean code is what you should always strive for. Here are 10 community hooks to help you write cleaner and more performant code.

10 React community hooks you should be using

Beautify GitHub profile

There is no better way to show off your skills than having an eye-grabbing GitHub profile, not only does it show you’re passionate and love your job, it will also make you stand out when applying for a job. In this article, I will show you what makes a good GitHub profile and how to build an awesome GitHub profile.

Beautify GitHub profile

Continuous integrations for VPS with GitHub actions

Set up your GitHub workflow and never worry about hosting, testing, and building your project again. This tutorial will show you how to set up your GitHub workflow so that you never have to worry about hosting your project on a server again. Code more and redeploy less.

Continuous integrations for VPS with GitHub actions

Become an amazing developer πŸ™Œ

  • Subscribe to my newsletter if you're interested in:
  • πŸ‘¨β€πŸ’» Web development in general
  • πŸ”₯ JavaScript
  • βš›

    React

  • πŸ’» Web 3.0
  • πŸ˜ƒ Helping you to become a great developer

Join over other developers growing their skills and learning the latest technologies