preloader
post-thumb

Last Update: January 31, 2025


BYauthor-thumberic


Keywords

Using Math Equations and LaTex Expressions in MDX Documents with Next.js

In this post, I will show you how to use math equations and LaTex expressions in MDX documents with next-mdx-remote.

Pages setup

Slug Page

/**
 * pages/blog/[...slug].js
 *
 */
import { MDXRemote } from 'next-mdx-remote'
import { serialize } from 'next-mdx-remote/serialize'

import rehypeHighlight from 'rehype-highlight'
import rehypeMathjax from 'rehype-mathjax'
import rehypeKatex from 'rehype-katex'
import remarkMath from 'remark-math'

import 'katex/dist/katex.min.css'

const options = {
  mdxOptions: {
      remarkPlugins: [remarkMath],
      rehypePlugins: [rehypeKatex, rehypeHighlight, rehypeMathjax],
  }
}

export default function BlogPost({ source }) {
  return <MDXRemote {...source} options={options} />
}

export async function getStaticProps({ params }) {
  const { slug } = params
  const source = `# Hello, world! $x^2 + y^2 = z^2$`
  const mdxSource = await serialize(source, options)

  return {
    props: {
      source: mdxSource,
    },
  }
}

layout


/**
 * components/layout/index.js
 * 
 * You may wanna copy the katex.min.js file to your public/js folder
 * cp node_modules/katex/dist/katex.min.js public/js/katex.min.js
 */

export default function Layout() {
  return (
    <div>
      <Header />
      <main>
        {children}
      </main>
      <Footer />
      {/* Inject katex.min.js here*/}
      {/*<script
        type="text/javascript"
        src="/js/katex.min.js"> */}
    </div>
  )
}

Webpack

In order to match the versions of the katex css and js files, you may need to add the following to your next.config.js file.

/**
 * next.config.js
 * 
 * we want to copy the katex dist files to the public folder
 * It may not necessarily work for you, but you can try it out
 */

const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
  webpack: (config) => {
    config.plugins = config.plugins || []
    config.plugins.push(
      new CopyPlugin({
        patterns: [
          { from: 'node_modules/katex/dist/katex.min.css', to: 'public/css/katex.min.css' },
          { from: 'node_modules/katex/dist/katex.min.js', to: 'public/js/katex.min.js' },
        ],
      })
    )

    return config
  }

Playing with MDX Documents Now

Math Equations

$x^2 + y^2 = z^2$

After parsing the equation with the above setup, katex will actually create two sets of elements: katex-mathml and katex-html.

Without Importing katex.min.css

If you don't import the katex.min.css file, it will show the following:

With Importing katex.min.css

// you can import it in the layout file
import 'katex/dist/katex.min.css'
// or import it in the page file

Results:

x2+y2=z2x^2 + y^2 = z^2

Another Example

$\frac{d}{dx} \left( e^{x^2} \right) = 2x e^{x^2}$

Results:

ddx(ex2)=2xex2\frac{d}{dx} \left( e^{x^2} \right) = 2x e^{x^2}

A few more examples:
The **Pythagorean equation**: $a=\sqrt{b^2 + c^2}$.
 
$P → Q ⟺ ~Q → ~P$
 
$(n + 1)^2 ≥ 2^n$

$$x = \frac{-b \pm \sqrt{b^{2} - 4ac}}{2a}$$


Results:

The Pythagorean equation: a=b2+c2a=\sqrt{b^2 + c^2}.

PQ Q PP → Q ⟺ ~Q → ~P

(n+1)22n(n + 1)^2 ≥ 2^n

x=b±b24ac2ax = \frac{-b \pm \sqrt{b^{2} - 4ac}}{2a}

LaTex Expressions

To display Latex expressions, you will have to use the code block and set the language to math. Otherwise you might get an error like the following:

Server Error
ReferenceError: cases is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

There might be other different types of errors as well:

Styled-components getting Expecting Unicode escape sequence \uXXXX
TypeError: Cannot read properties of undefined (reading 'mathFlowInside')


So to display LaTex expressions properly, please see the following example:

```math
\begin{cases}
2x + y = 7 \\
x - y = 1
\end{cases}
```

Results:

{2x+y=7xy=1\begin{cases} 2x + y = 7 \\ x - y = 1 \end{cases}

However, it doesn't work (as least with the version of katex I am using) if you include parentheses or brackets.

For example:

\[
\begin{cases}
2x + y = 7 \\
x - y = 1
\end{cases}
\]

Results:

\[ \begin{cases} 2x + y = 7 \\ x - y = 1 \end{cases} \]

It is the same for math expressions too, for example.

$$ \( x \)$$

Results:

\( x \)

After removing the parentheses, it works.

Results:

xx

Previous Article
post-thumb

Feb 05, 2025

Using Stable Diffusion WebUI Docker for Image Generation – A Newbie's Guide

In this article, I will guide you through installing, configuring, and using Stable Diffusion WebUI Docker to streamline your image generation workflow.

Next Article
post-thumb

Jan 29, 2025

How to Generate Images with AI Models on Your Own Computer

This article will show you how to generate images with AI models on your own computer.

agico

We transform visions into reality. We specializes in crafting digital experiences that captivate, engage, and innovate. With a fusion of creativity and expertise, we bring your ideas to life, one pixel at a time. Let's build the future together.

Copyright ©  2025  TYO Lab