This tutorial shows How to add images in NextJS components.

Next.js Image component example

Static sites use images to display the image.

Images can be accessed from the local project folder as well as from the remote URL.

The application contains a public folder containing all the image types.

In HTML pages, the img tag is used to display the images. We can use the HTML img tag in React components

    <img src="logo.svg" alt="logo" width="300px"/>

We can also use the img tag in the React component in the Next.js application. How do you optimize the images based on device type? So you need to write code to reduce image sizes and optimize images.

To fix all those issues, the NextJS framework provides an Image component(next/image) with extra below features.

  • Automatic optimization of local or CDN URL images: It reduces the size of an image without losing image quality.
  • Detects browser-supported formats and serves the image format accordingly.
  • Serve images with modern formats based on device type
  • Reduce Cumulative Layout Shift and improve Core Web Vitals
  • Overall page performance is improved with images
  • Dynamic image resizes for local and remote CDN paths

The first, is the Import component in the React component.

Load local images in Next.js applications

images such as png and SVG are placed in public or nested folders under the public folder.

files from the public folder are accessed directly with the base url. Image component contains src attribute to load from local or remote url

In React components, you can supply src attribute values with local image paths below ways.

  • Directly give the path that starts with /
  • Import images path with the import keyword.

The above ways are given in the below example component.

Here is an example for NextJS image component.

import type { NextPage } from 'next'
import Image from 'next/image'
import logo from '../public/logo.svg';

const PostImage: NextPage = () => {
  return (
    <>
      <Image src="/photo.svg" layout="fill"/>
      <Image src={logo} width="100px" height="200px"/>
    </>
  )
}

export default PostImage

Image component must use either layout or width and height, Otherwise, It gives the following exception Error: Image with src “vertical.SVG” must use “width” and “height” properties or “layout=‘fill’” property.

Image component attributes:

  • priority: It helps in reducing the largest Contentful Paint for each page. It gives the order of priority for loading an image.

layout:

NextJS image configuration

NextJS provides a configuration file that you can place in next.config.js in the project root directory.

It is a Nodejs module that you can configure. It contains different configurations that are used by the Node server during the build phase.

next.config.js

const nextConfig = {
    images: {
      domains: ['images.cdndomain.com'],
      loader: 'vercel',
      path: 'https://domain.com/myaccount/',
      deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
      imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
      formats: ['image/webp'],
      minimumCacheTTL: 60,
      disableStaticImages: true,
      dangerouslyAllowSVG: true,
      contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
  },

}
export default nextConfig
  • domains: It is a list of domain names that service images for optimizing images.

  • loader: It is a loader used for the optimization API of images.

    • default loader(squoosh) used during the build with next dev or next start command
    • vercel
    • Imgix
    • Cloudinary
    • Akamai
    • Custom
  • deviceSizes: A list of device sizes configured for the Image Component configured with layout is responsive or fill

  • imageSizes : List of images sizes generated in img tag for srcset attribute

  • formats: Formats supported by browsers using the request header Accept

  • minimumCacheTTL: Time to Live in seconds for caching images.

  • disableStaticImages: Disable static images using the import keyword in the react component

  • dangerouslyAllowSVG and contentSecurityPolicy : Allows to set value for Content Security header for images

How to use External URLs or remote images in Next.js applications

To load remotes in the NextJS app, Please follow the below steps

  • On your page component, use the Image tag as given below with src attribute containing remote url and other properties
<Image
   alt="alt text."
   src="https://images.domain.com/photo-sadfasdfasdfadsasd"
   width={600}
   height={400}
   layout="responsive"
/>
  • Next, Configure image domain mapping in next.config.js
module.exports = {
    images: {
        domains: ['images.domain.com'],
    },
}

How to load the images in eager or lazy?

The image component loads the images with lazy loading. It can be changed using below are two ways.

  • loading attribute added to component with loading={eager}
  • priority attribute Component added with priority={true} to make higher order.