Back to Resources

Next.js & Shiki: Beautiful Syntax Highlighting

Noteworthy Team

When building a developer blog or documentation site, code readability is paramount. Shiki is a powerful syntax highlighter that uses TextMate grammar (the same engine as VS Code) to provide accurate and beautiful highlighting.

In this guide, we'll show you how to integrate Shiki into a Next.js application using next-mdx-remote and rehype-pretty-code.

Why Shiki?

  • Accurate: Uses the same grammar as VS Code.
  • Zero Runtime: Highlighting happens at build time.
  • Themable: Supports all VS Code themes.

Installation

First, install the necessary dependencies:

npm install next-mdx-remote rehype-pretty-code shiki

Configuration

Here is how you can set up MDXRemote with rehype-pretty-code in your Next.js page component.

import { MDXRemote } from "next-mdx-remote/rsc";
import rehypePrettyCode from "rehype-pretty-code";
 
const options = {
  mdxOptions: {
    rehypePlugins: [
      [
        rehypePrettyCode,
        {
          theme: "github-dark",
          keepBackground: true,
        },
      ],
    ],
  },
};
 
export default function BlogPost({ source }) {
  return (
    <article className="prose dark:prose-invert">
      <MDXRemote source={source} options={options} />
    </article>
  );
}

Usage

Now, you can write your content in MDX and use code blocks like you normally would.

# My Post
 
Here is some code:
 
```typescript
const greeting = "Hello, Shiki!";
console.log(greeting);
```

Styling

rehype-pretty-code adds classes to your code blocks that you can target with CSS. For example, to handle line highlighting or added/removed lines in diffs.

/* Example CSS for line highlighting */
span[data-highlighted-line] {
  background-color: rgba(200, 200, 255, 0.1);
  display: block;
}

That's it! You now have professional-grade syntax highlighting in your Next.js app.