Skip to main content

Using Remark and Rehype Plugins with Next.js 14 and MDX

October 13, 2024

I have been redesigning and redeveloping my personal website for a couple of weeks now. Before when I was using the Pages Router, I used contentlayer with Remark and Rehype plugins to transform my MDX content. Since I was basically redoing my entire website and contentlayer is kind of no longer maintained, I thought it would be a good time to try @next/mdx instead.

What Are Remark and Rehype Plugins?

Remark and Rehype are tools used to transform markdown and HTML content respectively with plugins. Since React does not natively support markdown, the markdown content needs to be transformed into HTML before it can be rendered. This is where Remark and Rehype come in.

Get Remark and Rehype Plugins Working With Next.js 14

Aftering getting most of my setup done, I had to some time trying to figure out why the plugins were not working. I ended up finding the solution from a comment on a StackOverflow post and Next.js GitHub issue.

I was using an experimental feature that I probably should not have been using. When using Remark or Rehype plugins with Next.js, you have to make sure that the experimental feature mdxRs is either not defined or explicitly set to false in your next.config.mjs.

Besides this one hiccup that I had, the usage of Remark and Rehype plugins was pretty straightforward. You would just install and import the plugins into your next.config.mjs and then include them in your MDX options.

next.config.mjs
import createMDX from '@next/mdx'

// Imported plugins
import rehypePrismPlus from 'rehype-prism-plus'
import remarkGfm from 'remark-gfm'

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: { mdxRs: false }, // Do not use experimental mdxRs feature
  pageExtensions: ['mdx', 'ts', 'tsx'],
  reactStrictMode: true,
}

const withMDX = createMDX({
  options: {
    remarkPlugins: [remarkGfm], // Remark plugins
    rehypePlugins: [rehypePrismPlus], // Rehype plugins
  },
})

export default withMDX(nextConfig)