MDX is a file format where we can combine JSX with Markdown. It’s a language that’s compiled into JavaScript. MDX lets us use the React component directly in the markdown. We can say that MDX is a superset of Markdown that lets us include JSX inside the Markdown file.

MDX plugins:

MDX internally uses remark and rehype. Remark is a markdown processor, while rehype is an HTML processor, both of which are powered by plugin ecosystems. As React doesn’t recognize MDX directly, we need to first convert the MDX to HTML through remark and rehype.

Integrating local MDX files:

Required packages:

@next/mdx, @mdx-js/react and @mdx-js/loader

Configuration:

Inside next.config.js, add the following code:

const withMDX = require('@next/mdx')({
  extension: /\\.mdx?$/,
  options: {
    // If you use remark-gfm, you'll need to use next.config.mjs
    // as the package is ESM only
    // <https://github.com/remarkjs/remark-gfm#install>
    remarkPlugins: [require("remark-prism")],
    rehypePlugins: [],
    // If you use `MDXProvider`, uncomment the following line.
    // providerImportSource: "@mdx-js/react",
  },
})
const nextConfig = {
  // Configure pageExtensions to include md and mdx
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
  // Optionally, add any other Next.js config below
  reactStrictMode: true,
}

// Merge MDX config with Next.js config
module.exports = withMDX(nextConfig)

Here, remark-prism is used for syntax highlighting.

Integration:

Local MDX files can be used directly as components inside other React components.

For that, we need to add a layout component (say, named layout.tsx) like the following: It could be inside a folder named layouts

import { MDXProvider } from '@mdx-js/react';

interface LayoutProps {
  children: React.ReactNode;
}

export default function Layout({ children, ...props }: LayoutProps) {
  return (
    <MDXProvider components={customMdxComponents}>
      <div className="w-[80%] mx-auto p-6 text-gray-600 dark:text-gray-400">{children}</div>
    </MDXProvider>
  );
}

Now we can use this layout to export the MDX directly to the React component.

import Layout from '/layouts/layout.tsx';
# Heading level 1
export default ({ children }) => <Layout>{children}</Layout>;
import MDX from "mdxFileName.mdx";
export default function App() {
	return <MDX/>;
}

For resolving the typescript module-not-found error for the MDX file import, we can add a