Upgrading NextJS 12 to 14 (part 2: next/image)

Sat Nov 18 2023

NextJSnext/imageportfolio

As the second step of the upgrade, I had to deal with two errors related to the next/image component. Let's tackle them by order of appearance:

1. External images in next.config.js

The images.domains configuration is deprecated. Please use images.remotePatterns configuration instead.

In NextJS 12, when you used images hosted on a third-party server or a headless CMS (GpaphCMS in my case), in order to use them with next/image component, you had to declare the domain name they're hosted on by indicating it in the next.config.js file.

The pattern was

module.exports = {
⁠  images: {
⁠    domains: ['media.graphassets.com'],
  },
} 

In NextJS 14, image.domains configuration doesn't work anymore and the new structure requires image.remotePatterns usage as follows:

module.exports = {
⁠  images: {
⁠    remotePatterns: [
⁠      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        port: '',
        pathname: '/my-bucket/**',
      },
    ],
  },
} 

2. Deprecated objectFit

Image with src "https://media.***.com/***" has legacy prop "objectFit". Did you forget to run the codemod?
              <Image
                    src={project.coverImage.url}
                    height={project.coverImage.height}
                    width={project.coverImage.width}
                    objectFit='cover'
                    className='absolute'
                    alt={project.title}
              />

Before NextJS 13, you could have objectFit parameter in the <Image> component. It is now obsolete and you have to move it to the CSS Style. In my case, I just did it by adding an object-cover to the className of the tag, as I use TailwindCSS.

              <Image
                    src={project.coverImage.url}
                    height={project.coverImage.height}
                    width={project.coverImage.width}
                    className='absolute object-cover'
                    alt={project.title}
              />

And that was basically all I had to deal with while bringing my Image Optimisation up to date.

Made with Next.JS, Tailwind CSS, GraphCMS and Lots of