Setup MDX in Next.js

Setup MDX in Next.js

Minimum setup

Minimum working setup to use MDX file within Next.js.

References

Install dependencies

npm install @next/mdx @mdx-js/loader @mdx-js/react --save-dev

Modify next.config.mjs

// next.config.mjs is at the same directory location as the package.json file.

import createMDX from '@next/mdx';

const nextConfig = {}

// Configure pageExtensions to also include *.mdx
nextConfig.pageExtensions = ['jsx', 'mdx', 'ts', 'tsx']; 

const withMDX = createMDX({
    // Add markdown plugins here, as desired
})

export default withMDX(nextConfig)

Test the setup

  1. Add markdown syntax in a mdx page, e.g. hello.mdx
    {/*
        ./page/hello.mdx
        Remember: mdx is in fact an jsx file that allow markdown syntax.
        Markdown autolinks(e.g. <https://openwritings.net>) is not supported: https://github.com/mdx-js/mdx/issues/1049
    */}
    export const name = "Joe";
    
    #### Welcome
    My name is {name}.
    
  2. Open http://localhost:3000/hello
  3. It should will the markdown content.

Global styling mdx files

Change style for each HTML elements in mdx-components.js(It has to be .js). Place it in the same directory where package.json reside.

// mdx-components.js
import Image from 'next/image'

// This file allows you to provide custom React components
// to be used in MDX files. You can import and use any
// React component you want, including inline styles,
// components from other libraries, and more.

export function useMDXComponents(components) {
    return {
        // Allows customizing built-in components, e.g. to add styling.
        h1: ({ children }) => (<h1 style={{ color: 'red', fontSize: '50px' }}>{children}</h1>),
        h2: ({ children }) => (<h2 style={{ color: 'blue', fontSize: '40px' }}>{children}</h2>),
        h3: ({ children }) => (<h3 style={{ color: 'green', fontSize: '30px' }}>{children}</h3>),
        img: (props) => (
            <Image
                sizes="100vw"
                style={{ width: '100%', height: 'auto' }}
                {...props}
            />
        ),
        ...components,
    }
}

MDXProvider

  • https://github.com/orgs/mdx-js/discussions/2032
  • https://github.com/mdx-js/mdx/issues/821
  • https://didoesdigital.com/blog/nextjs-blog-04-markdown-styling/

Useful links

  • https://mdxjs.com/docs/extending-mdx/#list-of-plugins