t

Trevor Blades

AboutProjectsLabOSS
Subscribe

Using KaTeX With Gatsby and MDX

How to write mathematical notation in your blog posts

In my spiral and circle posts, I relied heavily on mathematical notation to explain formulas and equations that I used to build those features. Before then, I had never had to use mathematical notation in any web or computer context.

After some searching on the web, I learned that KaTeX was the right tool for the job. It takes a string of text written in TeX syntax and outputs nicely formatted mathematical notation.

💡 Did you know?

TeX's creator Donald Knuth promotes a pronunciation of /ˈtɛx/ (tekh), similar to the last sound of the German word "Bach". So you would say "kay-tekh" rather than "kay-tex".

In Markdown, it's common to see TeX\TeX written inside math blocks beginning and ending with $$.

$$
c = \sqrt{a^2 + b^2}
$$

The above Markdown becomes the following when processed by KaTeX\KaTeX:

c=a2+b2c = \sqrt{a^2 + b^2}

Processing the Markdown math blocks with KaTeX\KaTeX is not part of the basic offering of most Markdown renderers, and I needed to configure that part myself.

My website is built with Gatsby and MDX using gatsby-plugin-mdx, which accepts remark and rehype plugins as configuration options. Luckily there's a handful of plugins built for this purpose, such as remark-math, rehype-katex, and gatsby-remark-katex. Sadly, none of these libraries play nicely with the current stable version of MDX (1.6.x at the time of writing), only plain ol' Markdown.

I stumbled upon a GitHub issue related to this topic and experimented with the different "solutions" posted by others. The one that worked for me looks like this:

npm i remark-math@3 remark-html-katex@3 katex

It's important to install older versions of the two remark plugins since the newest versions are ESM only and Gatsby doesn't support ES modules in their gatsby-*.js files.

gatsby-config.js
module.exports = {
plugins: [
{
resolve: 'gatsby-plugin-mdx',
options: {
remarkPlugins: [require('remark-math'), require('remark-html-katex')]
}
}
]
};

Lastly, add the remark plugins to your gatsby-plugin-mdx configuration and import the stylesheet from the katex package into your client-side bundle.

gatsby-browser.js
import 'katex/dist/katex.css';

That's it! I hope you found this short guide to be helpful in setting up KaTeX\KaTeX in your Gatsby site. If not, it better have at least been interesting. 😋

Made with 🥥 in Burnaby, BC
© 2022 - Source code