Implement Next.js 10 next/image Component for Image Optimization

Next.js 10 has come up with an exciting feature for built-in Image Component and Automatic Image Optimization. Next.js Image Component is the extension of <img> element of HTML, for modern web. The Automatic Image Optimization allows for resizing, optimizing and serving images in modern web formats like Webp, when browser supports it.
We will discuss and implement the Next.js Image Component and observe image optimization with next/image. We will start the implementation of image component with a fresh Next.js project. Let’s begin!

1. Create Project Directory
Let’s create a project directory and name it as next_image. Open up the project directory on your favorite Code Editor and I’ll prefer vscode for it.

2. Initialize package.json
Open up the terminal containing the project directory and run following command that will create package.json file, which includes our project dependencies and scripts. Including -y on the command will generate the package file with all the defaults.

3. Install React, React Dom and Next
Now, we install React, React Dom and Next for our project with the following command. After installing these dependencies let’s make sure that our Next.js version is 10 or above.

4. Change Scripts of package.json
Add these scripts to the scripts section of package.json. Then, we can run the code with the command npm run dev.

5. Create index page
Now let’s create index.js file inside pages folder at the root level of the project since next.js will render the index page when you start your server. The next-image <Image /> component has 3 required props: src, width and height, that we will discuss later as well in details. Let’s add the image component in the index page with required props and get a dummy image from picsum. You can get the image from your cloud server or any other means in your project.

index.js

We will not be able to get the image still because there is one more thing left to do. We need to add the domain that is providing us the image. Exactly, we need to add picsum.photos in our next.config.js file. Are you thinking how to do? Come on, let’s create next.config.js at root level of the project and add following configuration. Remember that you can add any other domain that is providing you the image, for instance you can include storage.googleapis.com for image stored in Google Cloud Storage.

next.config.js

Boom! Let’s open of the default port in browser http://localhost:3000

Usage: Image Component

Let’s go through some of the great usage of next/image <Image /> component. I’ll try to include the implementation for the props as well.

Required props
As we have discussed above <Image /> component requires the following props:

1. src
This is required props which is the path or URL to the source image. As I’ve mentioned earlier while using external URL, we need to add domains to next.config.js like we did above.

2. width
This is required props which is the width of the image, in pixels that must be an integer without a unit. This is not required when you add layout="fill" .

3. height
This is required props which is the height of the image, in pixels that must be an integer without a unit. This is not required when you add layout="fill" .

Example of <Image /> component with only required props is displayed in example above. Let me remind you again,

Optional Props

1. layout
It defines the layout behavior of image as the viewport changes size which defaults to intrinsic .
Fixed : The image dimensions will not be changed as viewport changes (without responsiveness) which is similar to the native element img .
Intrinsic : The image will scale the dimensions down for smaller viewports but maintain the original dimensions for larger viewports.
responsive : The image will scale the dimensions down for smaller viewports and scale up for larger viewports.
fill : The image will stretch both width and height to the dimensions of the parent element.

2 . loader
Loader is referred to the custom function used to resolve URLs. It defaults to images object in next.config.js . loader returns a string, given with the parameters
- src
- width
- quality
Example:

3. size
Device Sizes: If we are known with the expected device widths from the users of our site, we can specify the list of device width breakpoints using deviceSizes . These widths are used when next/image component uses layout="responsive" or layout="fill" which in return serves the correct image for the device visiting the site.
Default for deviceSizes when no configuration is provided is:

Image Sizes: We can also specify a list of image widths using imageSizes property. These widths should be generally smaller than the width defined in deviceSizes because the arrays will be concatenated. These widths are used when next-image component uses layout="fixed" or layout="intrinsic" .
Default for imageSizes when no configuration is provided is:

4. quality
It defines the quality of the image from 1 to 100 where 100 is the best quality. Default value is 75 .
Example:

5. priority
It defines the high priority and preload of the image. When this props is used the image will be considered as high priority and preload. It should be only used when the image is visible above the fold. Default is false unless you add it.

Advance props

1. objectFit
It defines how the image should be resized to fit its container.

2. objectPosition
It defines the alignment of image within the element’s box.
Let’s observe an example of how objectFit and objectPosition can be given:

3. loading
The default loading behavior is lazy in next/image. There is following different between two of them:
The lazy props defers/postpones loading the image until it reaches a calculated distance from the viewport.
The eager props immediately loads the image.

4. unoptimized
Talking about unoptimized props, the image is served as it is instead of changing any of quality, size or format. It defaults to false .

We talked about some of the uses of next/image component. Now let’s explore briefly about the exciting feature provided by next-image for image caching which has been great milestone for image optimization working with Next.js.

Caching

With the use of next/image images are optimized dynamically upon request and stored in <distDir>/cache/images (in our case distDir is .next ) directory. Then the optimized image file is served for subsequent requests until the expiration is reached. If a request is made that matches the cached but expired file, the cached file is deleted before generating a new optimized image and cache the new file.
Expiration is defined and denoted by upstream server’s Cache-Control header.
Default life for the cache in next-image is 60 second. If s-maxage is found in Cache-Control , it is used. If no s-maxage is found, then max-age is used. If no max-age is found, then 60 seconds is used by default.
Convenient way to reduce the total number of possible generated images is configuring deviceSizes and imageSizes as I’ve mentioned earlier.

Conclusion

We covered up some of the exciting facts of Image Component provided by Next.js 10 and their implementations. If you have some difficulties to understand about next/image and image optimization please feel free to drops of queries in the comment section below. I have added the repository link for the sample project that we have implemented above just for the reference. Thanks for reading it to the end. See you in the next article.
Stay Tuned!

Github Link: https://github.com/SudeepTimalsina/next-image

Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store