'React components and math expressions in .mdx file are not rendering correctly in Next.js application

My custom React components when imported in a .mdx file, are not being rendered at all. The math expressions in the .mdx file either render unformatted or throw parsing errors in spite of following the configuration instructions in the Next.js (https://nextjs.org/docs/advanced-features/using-mdx) and MDX documentation (https://mdxjs.com/guides/math/).

Here are my configurations:

//next.config.js
/** @type {import('next').NextConfig} */

const remarkMath = import('remark-math');
const rehypeKatex = import('rehype-katex');

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [remarkMath],
    rehypePlugins: [rehypeKatex],
    // If you use `MDXProvider`, uncomment the following line.
    // providerImportSource: "@mdx-js/react",
  },
})
module.exports = withMDX({
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
  reactStrictMode: true
})


//package.json

  "dependencies": {
    "@mdx-js/loader": "^2.1.1",
    "@next/mdx": "^12.1.5",
    "fs": "^0.0.1-security",
    "gray-matter": "^4.0.3",
    "next": "12.1.5",
    "path": "^0.12.7",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "recharts": "^2.1.9",
    "rehype-katex": "^6.0.2",
    "remark": "^14.0.2",
    "remark-html": "^15.0.1",
    "remark-math": "^5.1.1"
  },
  "devDependencies": {
    "@types/node": "17.0.25",
    "@types/react": "18.0.5",
    "@types/react-dom": "18.0.1",
    "eslint": "8.13.0",
    "eslint-config-next": "12.1.5",
    "typescript": "4.6.3"
  }

Here is my custom Document component to allow the app to fetch the katex.min.css file:

//_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
    return (
        <Html>
            <Head>
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-KiWOvVjnN8qwAZbuQyWDIbfCLFhLXNETzBQjA/92pIowpC0d2O3nppDGQVgwd2nB" crossOrigin="anonymous"/>
            </Head>
            <body>
                <Main />
                <NextScript />
            </body>
        </Html>
    )
}

What is it that I'm not doing correctly?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source