Using Next.js Image Component for Optimized Images

Jul 26, 2023

The Next.js Image component is a powerful feature that provides several performance enhancements over the traditional HTML image tag. It ensures that images are served in appropriate sizes for each device, uses modern image formats, and minimally impacts page layout, all of which contribute to faster page loads. This component can serve both local and remote images, making it a flexible choice for any Next.js project.

Serving Local Images

To start, let's take a look at how to serve local images using the Next.js Image component. Import the component from next/image and then you can use it in your code. Here's a simple example:

import Image from 'next/image' import lazar from '../public/lazar.png' export default function Home( ) { return (<Image src={lazar} alt="Lazar's Image" /> ) }

In the code above, the Image component is used to display a local image named 'lazar.png'. Unlike traditional image tags, the src prop here receives the imported image directly.

Serving Remote Images

Serving remote images is also straightforward, with one additional step required for security reasons. You need to define the domains of the images you want to fetch in the next.config.js file of your project. This is a mandatory step as Next.js needs to know the domains to accept images from. Here's how to do it:

// next.config.js module.exports = { images: { domains: ['pbs.twimg.com'], }, }

Then, you can use the Image component in your component just like before, but this time with a remote URL:

import Image from 'next/image' export default function Home( ) { return ( <> <Imagesrc="https://pbs.twimg.com/profile_images/1308010958862905345/-SGZioPb_400x400.jpg" alt="Remote Picture of Lazar"width={250} height={250} /> </> ) }

In the example above, we have an Image component which loads an image from a remote URL. Notice the width and height props in the Image component. These are needed for the layout calculation to prevent layout shifts.

Recap

The Next.js Image component provides a way to serve local and remote images with several performance optimizations over traditional image tags. It ensures faster page loads, provides visual stability, and supports on-demand image resizing. For remote images, you need to add the domains of the images to the Next.js configuration in next.config.js. By using this component, you can ensure your images are highly optimized for your Next.js project.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed sapien quam. Sed dapibus est id enim facilisis, at posuere turpis adipiscing. Quisque sit amet dui dui.

Call To Action

Stay connected with news and updates!

Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.

We hate SPAM. We will never sell your information, for any reason.