🚀 Use LAUNCH75 Promo Code At Checkout for 75% Off. Limited Time. Expires in 3 days, 19 hours, 45 minutes, 35 seconds.

How to Add Syntax Highlighting to Next.js with PrismJS

Learn how to add syntax highlighting to Next.js using PrismJS during runtime.

If you'd like to add syntax highlighting at build time, see How To Add Syntax Highlighting To Markdown With Next.js and Rehype Prism.

Step 1: Initialize Next.js project

npx create-next-app@latest

Step 2: Install PrismJS

npm install prismjs
npm i --save-dev @types/prismjs

Step 3: Create a PrismLoader component


"use client";

import { useEffect } from "react";
import Prism from "prismjs";
import "prismjs/themes/prism-okaidia.css";
import "prismjs/components/prism-typescript";

export default function PrismLoader() {
  useEffect(() => {
  }, []);
  return <div className="hidden"></div>;

Feel free to import a different theme and add additional languages.

Step 4: Use the PrismLoader in any page that needs syntax highlighting


import PrismLoader from "@/components/prism-loader";

export default function Home() {
  return (
      <pre className="language-js">
        <code className="language-js">console.log("hello world")</code>
      <pre className="language-ts">
        <code className="language-ts">console.log("hello world")</code>
      <PrismLoader />

Note: JavaScript is included as a default language. Some languages, like TypeScript, need to be imported.

Related Courses

Learn how to build A Markdown Powered Static Blog with NextJS App Router.