hard at work
Shares

Using Next.js Image Component in MDX

Last updated: Jul 6, 2024

There is a "bug?" in MDX that prevents using the Image component from Next.js directly. In this article, we show one way to get around that error.

The Error

Error: Cannot access Image.propTypes on the server. You cannot dot into a client module from a server component. You can only pass the imported name through.

This occurs when trying to use the Image components within MDX:

(inside mdx)
<Image src="" width="" height="" alt="" />

The Solution

The solution, for some reason, is to wrap the Image component in a custom component and import that:

(mdx-image.tsx)
import Image, { ImageProps } from 'next/image';

export default function MDXImage(props: ImageProps) {
  return <Image {...props } alt = { props.alt } />;
}

(page.tsx)
import MDXImage as Image from '@ui/mdx-image';

const components = {
     Image,
    ...(other components)
}

...

(in jsx part of page)
<MDXRemote source={content} components={components} />

Then you can use the Image component in MDX as you normally would:

(in mdx)
<Image src="/images/blog/dev.jpg" width="1024" height="640" alt="example image" />