Back to overview
Mountains with Next.js logo
Using the Next.js Image Component with MDX
December 31, 2020

Photo by Samuel Ferrara.

Happy new years! 2020 was a rough year and here's hoping 2021 will be a better year!

Recently I've been experimenting with Next.js, and I have found it amazing. I've been trying to recreate my portfolio website using Next.js, which is currently written in Gatsby. I've noticed from my experimentation that Next.js does not handle a lot of the details, unlike Gatsby, where plugins do much of the heavy lifting. With Next.js, images and sourcing MDX is your responsibility (a pro and a con, depending on what you need).

Next.js Image Component and Layout Shift

Recently Vercel released Next.js 10, which includes an image component that handles image optimization similar to the one in Gatsby. Unlike the Gatsby component, Next.js's component requires that you provide the image's width and height to prevent layout shift (Gatsby handles this internally), which will be important for SEO. You can read more here.

Images are always rendered in such a way as to avoid Cumulative Layout Shift, a Core Web Vital that Google is going to use in search ranking.

Gist of Layout Shift

You know how you click on a website, and you see the initial page load without seeing the images, and then the images start loading in, causing things to move around? I and many users find this annoying. Well, by providing the height and width, Next.js can prevent this "layout shift" to improve user experience (it's crucial since Google is going to use it in search ranking).

The Problem

Well, Next.js's unopinionated nature has made it difficult to find a straightforward way to use optimized images in an MDX blog. Additionally, I have been using next-mdx-remote ( link) for sourcing and parsing MDX data, but the documentation does not provide any information about using the Next.js image component. I have read a few articles (see footnotes) about the subject but still nothing. So I created a custom solution!

The Solution

I've created a rehype plugin that attaches the image's height and width to its properties. This allows you to use them in your custom MDX components. You can create a custom img MDX component that uses the Next.js image component with the provided height and width.

The Code

Full code is on my GitHub repo.

First, you will need to install unist-util-visit, image-size.

yarn add unist-util-visit image-size

Here's the example blog post.

# Example MDX

![image](/snippets/other/workshops1.jpg)

![other](/snippets/other/default-seo-image.png)

Here's how you source and create the MDX data. Do note that I am using example.tsx for a single blog post, but in reality, you would want to source multiple MDX files and thus might want to use a dynamic route like /pages/blog/[blogid].tsx

import type { MDXProviderComponentsProp } from '@mdx-js/react';
import { promisify } from 'util';
import type { GetStaticProps } from 'next';
import hydrate from 'next-mdx-remote/hydrate';
import renderToString from 'next-mdx-remote/render-to-string';
import NextImage from 'next/image';
import path from 'path';
import imageMetadata from 'plugins/image-metadata';

export interface ExampleBlogPostProps {
  body: string;
}

const mdxComponents: MDXProviderComponentsProp = {
  // Custom image - here you can customize the image layout: https://nextjs.org/docs/api-reference/next/image#layout
  img: ({ src, height, width, ...rest }) => (
    // layout="responsive" makes the image fill the container width wise - I find it looks nicer for blog posts
    <NextImage layout="responsive" src={src} height={height} width={width} {...rest} />
  )
};

export const getStaticProps: GetStaticProps = async () => {
  // Source in the file
  const content = await (
    await promisify(fs.readFile)(path.join(process.cwd(), 'content/snippets', 'other.mdx'))
  )
    // await fsPromise.readFile(path.join(process.cwd(), 'posts', 'example.mdx'))
    .toString();

  // If you have metadata, parse it here with `grey-matter` or something else!

  const body = await renderToString(content, {
    components: mdxComponents,
    scope: {},
    mdxOptions: {
      rehypePlugins: [imageMetadata]
    }
  });

  return { props: { body } };
};

const ExampleBlogPost: React.FC<ExampleBlogPostProps> = ({ body }) => {
  const content = hydrate(body, { components: mdxComponents });

  return <div>{content}</div>;
};

export default ExampleBlogPost;

Here is the rehype plugin that attaches the width and height of the image to the image component.

// Similiar structure to:
// https://github.com/JS-DevTools/rehype-inline-svg/blob/master/src/inline-svg.ts
import imageSize from 'image-size';
import path from 'path';
import { Processor } from 'unified';
import { Node } from 'unist';
import visit from 'unist-util-visit';
import { promisify } from 'util';
import { VFile } from 'vfile';

const sizeOf = promisify(imageSize);

/**
 * An `<img>` HAST node
 */
interface ImageNode extends Node {
  type: 'element';
  tagName: 'img';
  properties: {
    src: string;
    height?: number;
    width?: number;
  };
}

/**
 * Determines whether the given HAST node is an `<img>` element.
 */
function isImageNode(node: Node): node is ImageNode {
  const img = node as ImageNode;
  return (
    img.type === 'element' &&
    img.tagName === 'img' &&
    img.properties &&
    typeof img.properties.src === 'string'
  );
}

/**
 * Filters out non absolute paths from the public folder.
 */
function filterImageNode(node: ImageNode): boolean {
  return node.properties.src.startsWith('/');
}

/**
 * Adds the image's `height` and `width` to it's properties.
 */
async function addMetadata(node: ImageNode): Promise<void> {
  const res = await sizeOf(path.join(process.cwd(), 'public', node.properties.src));

  if (!res) throw Error(`Invalid image with src "${node.properties.src}"`);

  node.properties.width = res.width;
  node.properties.height = res.height;
}

/**
 * This is a Rehype plugin that finds image `<img>` elements and adds the height and width to the properties.
 * Read more about Next.js image: https://nextjs.org/docs/api-reference/next/image#layout
 */
export default function imageMetadata(this: Processor) {
  return async function transformer(tree: Node, file: VFile): Promise<Node> {
    const imgNodes: ImageNode[] = [];

    visit(tree, 'element', (node) => {
      if (isImageNode(node) && filterImageNode(node)) {
        imgNodes.push(node);
      }
    });

    for (const node of imgNodes) {
      await addMetadata(node);
    }

    return tree;
  };
}

Caveats

This only works with the markdown image form, ie: ![image](/path/to/image) and does not work with JSX components. If you use a JSX image component you will need to manually figure out the height and width.

Conclusion

With this setup, I can now easily add more optimized images to my MDX blog post without finding the height and width. I have recently been learning Next.js, so there may be a better way of doing this. I hope that next-mdx-remote or the Next.js team posts more information about using images inside an MDX blog. I hope you enjoyed this post. Have a great day!

Footnotes