Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use syntax code highlighting using next-mdx-remote?

I'm trying to highlight my code syntax using next-mdx-remote in my Nextjs based page. I'm getting my markdown format from graphcms and rendering it like this :


import { serialize } from "next-mdx-remote/serialize"
import { MDXRemote } from "next-mdx-remote"
import rehypeHighlight from "rehype-highlight"


export async function getStaticProps({ params }: any) {
  const data = await getPostDetail(params?.slug)

  const source = data?.content?.markdown
  const mdxSource = await serialize(source, {
    mdxOptions: { rehypePlugins: [rehypeHighlight] },
  })

  return {
    props: {
      posts: data,
      mdxSource: mdxSource,
    },
  }
}


function Post({mdxSource}){
  return(
    <MDXRemote {...mdxSource} />
  )
}

Unfortunately, the code blocks gets rendered like normal text fields and doesn't do anything.

I'm not sure what I'm missing here, the official documentation doesn't clarify this as well

like image 259
anshul Avatar asked Jun 25 '26 02:06

anshul


2 Answers

According to mdx docs you want to include the below link somewhere in your header.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/github-dark.min.css"></link>

let me know if it doesn't work. it works for me at the least.

like image 169
0xbe1 Avatar answered Jun 27 '26 15:06

0xbe1


I think you need to add some css? For example

import "highlight.js/styles/atom-one-dark.css";

like image 21
al3xg Avatar answered Jun 27 '26 15:06

al3xg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!