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
/components/prism-loader.tsx
"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(() => {
Prism.highlightAll();
}, []);
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
/app/page.tsx
import PrismLoader from "@/components/prism-loader";
export default function Home() {
return (
<div>
<pre className="language-js">
<code className="language-js">console.log("hello world")</code>
</pre>
<pre className="language-ts">
<code className="language-ts">console.log("hello world")</code>
</pre>
<PrismLoader />
</div>
);
}
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.