Optimization image in Nextjs

Next.js have many features in-build one of them is next/image image component which helps to optimizes the nextjs web page and increases the page loading speed.

The Next.js Image component extends the HTML <img> element with additional features for automatic image optimization, we can use this same as html img tag

First lets create a image by using the Image component, pass the props which are required to show image.

src, width, height and alt props are required in Image component.

1import Image from 'next/image' 2 3export default function Page() { 4 return ( 5 <Image 6 src="/image_url.jpg" 7 width={500} 8 height={500} 9 alt="Place image alt text" 10 /> 11 ) 12 }

Required Props in Nextjs Image

Optional Props in Nextjs Image

Nextjs Image placeholder

Placeholder can have these values blur, empty, or data:image/.... Defaults to empty, When the value is set blur, then the blurDataURL property will be used as the placeholder.

For images which are imported from public static folder then blurDataURL will be automatically populated, except when the image is detected to be animated.

For dynamic image url you have to pass the blurDataURL as needed.

When placeholder is set to empty, then there will be no placeholder while the image is loading, only empty space.

Advanced Optional Props in Nextjs Image

Used 'use client' for onLoadingComplete, onLoad, onError because these are client side events.

Configuration Image Options

Configure only to access image from particular domain, this will helps to load image from valid source.

remotePatterns helps to load image from valid host which matches the pattern and the protocol should be https

1module.exports = { 2 images: { 3 remotePatterns: [ 4 { 5 protocol: 'https', 6 hostname: '**.example.com', 7 }, 8 ], 9 }, 10}

Wildcard patterns can be used for both pathname and hostname and have the following syntax:

Similar to remotePatterns, domains configuration can be used to provide a list of allowed hostnames for external images, domains configuration does not support wildcard pattern matching and it cannot restrict protocol, port, or pathname.

1module.exports = { 2 images: { 3 domains: ['assets.example.com', 'static.example.com'], 4 }, 5}