When using math plugins like rehype-katex or rehype-mathjax, rehype-sanitize will strip the complex markup and inline styles they generate by default.
To allow math, do not try to allow all inline styles (which is unsafe). Instead, sanitize first using a custom schema that allows the specific classes used by the math plugins, and then run the math plugin. This ensures the math markup is generated on already-sanitized content.
import rehypeKatex from 'rehype-katex'
import rehypeParse from 'rehype-parse'
import rehypeSanitize, {defaultSchema} from 'rehype-sanitize'
import rehypeStringify from 'rehype-stringify'
import {unified} from 'unified'
const file = await unified()
.use(rehypeParse, {fragment: true})
.use(rehypeSanitize, {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
// Allow the specific classes used by math plugins
code: [['className', /^language-./, 'math-inline', 'math-display']]
}
})
.use(rehypeKatex)
.use(rehypeStringify)
.process('<code class="math-inline">L</code>')