How to Add Code Highlighting in Next.js with CodeHike
A step-by-step guide for frontend engineers to configure CodeHike for beautiful code highlighting in your Next.js blog.
#How to Add Code Highlighting in Next.js with CodeHike
Code blocks are essential for technical blogs, and great syntax highlighting makes your content shine. CodeHike is a modern, flexible code highlighter that supports 200+ languages, themes, and even custom code block components.
This guide will show you how to set up CodeHike in a Next.js project using MDX, with tips for customization and theme support.
#Why CodeHike?
- Beautiful themes: GitHub-like light/dark, plus many more
- MDX integration: Works seamlessly with React/Next.js
- Customizable: Add language labels, icons, and more
- Fast: Async highlighting for large code blocks
#1. Install CodeHike
First, add CodeHike and its peer dependencies:
npm install @code-hike/mdx @code-hike/react @code-hike/lighter
#2. Configure MDX to Use CodeHike
Update your MDX configuration to use CodeHike plugins. In your Next.js app, this is usually in your MDX loader or page config:
import { remarkCodeHike } from '@code-hike/mdx/remark'import { recmaCodeHike } from '@code-hike/mdx/recma'import githubTheme from '@code-hike/mdx/themes/github-from-css'const mdxOptions = {remarkPlugins: [[remarkCodeHike, { theme: githubTheme }]],recmaPlugins: [recmaCodeHike],}
#3. Create a Custom Code Block Component
To customize how code blocks look (e.g., add language labels or icons), create a component like this:
// src/components/blog/CodeHighlight.tsximport { CHCode } from '@code-hike/react'export async function MyCode(props: any) {const lang = props.lang || 'text'return (<div className="relative mb-4"><div className="rounded-t bg-gray-100 px-3 py-1 text-xs font-semibold dark:bg-gray-800">{lang}</div><CHCode {...props} /></div>)}
You can map this component in your MDX provider or page config so all code blocks use it.
#4. Add CodeHike CSS Variables
Add the required CSS variables for CodeHike’s themes to your global CSS (e.g., src/styles/globals.css). For GitHub themes:
:root {--ch-0: #fff;--ch-3: #24292f;--ch-8: #d1d5da;/* ...more variables from CodeHike docs... */}[data-theme='dark'] {--ch-0: #0d1117;--ch-3: #c9d1d9;--ch-8: #30363d;/* ...more variables for dark mode... */}
#5. Use in Your Blog Posts
Now, any code block in your MDX files will be beautifully highlighted:
function hello(name: string) {return `Hello, ${name}!`}
#6. (Optional) Add Language Icons
To show a language icon above each code block, use a library like react-icons and map language names to icons in your custom code block component.
#Conclusion
CodeHike makes code blocks in your blog look professional and readable. With a few steps, you get beautiful, theme-aware syntax highlighting that works with MDX and Next.js.
Happy blogging!