Introduction: Why Did next/image
Appear on the Front-end Map? đ¤
Hello everyone! If you have a certain level of âseniorityâ in the world of front-end development, you probably remember the days of âwrestlingâ with optimizing images for websites. From searching for tools to âcompressâ image sizes to struggling with responsive image setups to display ânicelyâ on all types of devices⌠Frankly, effective image management has never been an easy task. Sometimes, it even becomes a real pain point. đŤ
As Next.js gradually established itself as a leading framework for building modern web applications, the problem of image optimization became more urgent than ever. Although Next.js has excellently solved many performance and user experience issues, displaying images optimally remained a significant challenge. It wasnât that Next.js was âfacing difficulties,â but rather that image optimization is inherently a âtricky problemâ common to web developers. For this very reason, the next/image
component was introduced in Next.js 10 (late 2020) as an âall-in-oneâ solution. This is not just a ârefurbishedâ <img>
tag, but a powerful tool, âtailor-madeâ by the Next.js team to thoroughly address the âchallengesâ in managing and displaying images effectively.
In this article, you and I will together ârevisitâ the development journey of next/image
from its early days to the present. We will explore the important changes and valuable improvements that this component has undergone in different Next.js versions. Letâs âbegin this journeyâ together! đ
The Challenges in Image Management Before next/image
đ
Before next/image
became a part of Next.js, managing images on the web often faced certain challenges. Although browsers provided basic image optimization mechanisms and there were external tools supporting React applications, ensuring optimal image performance still required effort from developers.
-
Optimizing Loading Performance: Displaying many images, especially large ones, can slow down page load times. While techniques like lazy loading could be implemented manually, managing and configuring them effectively across the entire application could be complex.
-
Preventing Cumulative Layout Shift (CLS): Browsers render images according to the document flow, and if image dimensions are not predefined, loading images can cause the layout to âjump,â affecting the user experience. Proactively managing the size and aspect ratio of images is necessary to avoid this issue.
-
Managing Responsive Image Versions: To serve appropriate images for various screen sizes and resolutions, developers often needed to create and manage multiple versions of the same image. This process could be time-consuming and laborious without an integrated solution.
In that context, next/image
was introduced as an integrated and convenient solution within the Next.js ecosystem, helping to automate many aspects of image optimization, easily supporting lazy loading, and minimizing CLS issues without requiring complex initial configurations.
Next.js 10 (2020): The âInaugural Shotâ of next/image
đ§ą
Next.js 10, released in late 2020, marked the appearance of next/image
. This first version brought incredibly powerful features, solving many performance and image optimization issues that we hadnât encountered before.
The First Foundational âBricksâ
-
âHands-Offâ Image Optimization: This is perhaps the âtopâ feature that garnered the most user attention. Next.js automatically optimizes images during the project build, significantly reducing image file sizes while maintaining good display quality. Now, we donât need to âtouchâ any external optimization tools anymore. đŞ
How It Works: When you use the
next/image
component, Next.js automatically processes the image, creating multiple versions with different sizes based on browser requirements. This helps reduce bandwidth usage and significantly improves page load times. -
âSmartâ Lazy Loading: Images are only loaded when the user scrolls the page close to their display area. This helps the website load significantly faster, especially useful for pages with many images.
-
Practical Benefits: Reduces bandwidth consumption and page load times, providing a smoother user experience.
-
Typical Example: For blogs or galleries with many images, lazy loading significantly improves initial page load performance.
-
-
âBlockingâ CLS Thanks to Size Optimization: Next.js allows us to explicitly declare the
width
andheight
of the image. This helps the browser âknow in advanceâ the size of the image, thereby âpreparing spaceâ and avoiding the unpleasant layout âjumpingâ when the image is fully loaded (Cumulative Layout Shift - CLS).Code Example:
import Image from "next/image"; import myImage from "../public/my-image.jpg"; function HomePage() { return ( <div> <Image src={myImage} alt="My Image" width={500} height={300} /> </div> ); } export default HomePage;
-
âPartneringâ With Multiple Formats:
next/image
supports modern image formats like WebP, AVIF (when configured), further reducing image file sizes without affecting display quality.
Next.js 11 (2021): Small But Valuable Improvements
Following the success of version 10, Next.js 11 continued to âfine-tuneâ next/image
with some notable improvements, focusing on enhancing performance and user experience. Although there were no major API changes, these âsilentâ improvements brought practical benefits.
-
âBroaderâ Support for AVIF: The advanced AVIF image encoding format is better supported. This means that when a userâs browser supports AVIF and you have configured Next.js to use this format,
next/image
will automatically serve images in AVIF format. Although there are no direct code changes in the component, you can configure AVIF support innext.config.js
:// next.config.js module.exports = { images: { formats: ["image/avif", "image/webp"], // Add 'image/avif' to the list }, };
When configured as above, and you use
next/image
as usual:import Image from "next/image"; import myImage from "../public/my-image.jpg"; function HomePage() { return ( <div> <Image src={myImage} alt="My Image" width={500} height={300} /> </div> ); } export default HomePage;
Next.js will automatically âprioritizeâ serving the AVIF version (if available and supported by the browser), significantly reducing image file sizes compared to traditional formats like JPEG or PNG while maintaining excellent image quality. You donât need to change the code using
next/image
, just the configuration. -
âSmootherâ Lazy Loading: Lazy loading capabilities are improved, especially with components like sliders and video thumbnails. While lazy loading worked well in Next.js 10, Next.js 11 optimized this mechanism to ensure that images in dynamic components like sliders are loaded more efficiently when the user interacts. In terms of code, you still use
next/image
as usual, and the lazy loading mechanism has been improved âunder the hoodâ:import Image from "next/image"; import sliderImage1 from "../public/slider-image-1.jpg"; import sliderImage2 from "../public/slider-image-2.jpg"; function ImageSlider() { return ( <div> {/* Assume this is a slider component */} <Image src={sliderImage1} alt="Slider Image 1" width={500} height={300} /> <Image src={sliderImage2} alt="Slider Image 2" width={500} height={300} /> </div> ); } export default ImageSlider;
In Next.js 11, youâll notice that images in the slider tend to load more âsmoothlyâ when the user switches between slides, thanks to lazy loading improvements.
-
More âAccurateâ Size Calculation: The automatic image size calculation mechanism is improved for accuracy, helping to minimize CLS issues. Although you should still declare
width
andheight
to avoid CLS, Next.js 11 has improved its ability to infer image sizes in some cases, especially when working with images from external sources. This means that in certain situations, Next.js can âguessâ the image size more accurately, even if you donât provide it explicitly, helping to reduce the risk of CLS. However, explicitly declaring the dimensions is still the best way to ensure no CLS.
Next.js 12 (2021): Significant Performance Enhancements
Although next/image
appeared in Next.js 10, Next.js 12 continued to bring significant performance improvements to this component, focusing on optimizing the build process and caching capabilities.
-
Build Performance Optimization: The image processing workflow during the build process has been optimized. This means that the time required for Next.js to optimize images when you build your project has been significantly reduced, especially for large projects with a large number of images. This change happens âunder the hoodâ of Next.js, and you will see a noticeable improvement when building large projects. You donât need to change any code, just upgrade to Next.js 12. Build times will improve automatically.
-
Improved Caching Capabilities: The image caching mechanism has been improved, helping to minimize unnecessary requests to the server, thereby increasing page load speeds for users. Next.js 12 has optimized how images are cached on both the server and client sides. This means that when a user visits your website a second time (or reloads the page), images will load faster from the cache, reducing the load on the server and improving the user experience.
You can see the improved caching mechanism more clearly when configuring custom image loaders. For example, if you use an external CDN, you can configure the loader to maximize the caching capabilities of that CDN.
// next.config.js module.exports = { images: { loader: "custom", loaderFile: "./my-image-loader.js", }, };
And in
my-image-loader.js
:export default function myImageLoader({ src, width, quality }) { // Logic to create the image URL from your CDN, including leveraging cache headers const url = `https://my-cdn.example.com/${src}?w=${width}&q=${ quality || 75 }`; return url; }
Although the code above doesnât directly show the cache improvements in Next.js 12, using a custom image loader allows you to take advantage of the caching enhancements that Next.js 12 brings, helping images load faster from the CDN when cached.
Next.js 13 (2022): A âTransformationâ with the App Router and the Convenient âfillâ Property đ
Version 13 of Next.js marks a major shift with the introduction of the App Router. next/image
was also âredesignedâ to be compatible and work well in this new environment, while also bringing new and extremely useful features.
âValuableâ Changes
-
âIntegrationâ with the App Router:
next/image
works seamlessly in both the Pages Router and the App Router. However, the usage is slightly different depending on the type of router you are using.- Example Usage in the App Router:
import Image from "next/image"; import myImage from "@/app/public/my-image.jpg"; export default function HomePage() { return ( <div> <Image src={myImage} alt="My Image" width={500} height={300} /> </div> ); }
-
âFilling Every Spaceâ with the âfillâ Layout: This is an extremely useful new property that makes it easy to create responsive image containers without having to specify specific
width
andheight
. The image will automatically âfillâ the space of its parent element.Code Example: Using the âfillâ Layout
import Image from "next/image"; import myImage from "../public/my-image.jpg"; function ImageFill() { return ( <div style={{ position: "relative", width: "100%", height: "400px" }}> <Image src={myImage} alt="My Image" fill style={{ objectFit: "cover" }} // Ensure the image doesn't get distorted /> </div> ); } export default ImageFill;
-
âSpecifyingâ Sizes with the
sizes
Property: When combined withlayout="responsive"
orlayout="fill"
, thesizes
property allows you to provide âhintsâ about image sizes to the browser. This helps the browser select the most appropriate image version from the start, optimizing image loading.Specific Explanation: Helps the browser choose the most optimal image size based on screen size and resolution, thereby reducing unnecessary bandwidth usage.
Next.js 14 (2023): Focus on Performance and Security đĄď¸
Next.js 14 continues to âpolishâ next/image
, focusing on improving performance and enhancing security.
Important Highlights
-
âPrioritizingâ Loading Important Images with the
priority
Property: Thepriority
property is introduced to âmarkâ important images that need to be loaded early (e.g., hero images, logos). When this property is set, the image will be prioritized for loading, significantly improving the Largest Contentful Paint (LCP) score.- Clearly Noticeable Benefits: Significantly improves LCP, providing a smoother user experience and improving SEO rankings.
-
Even More âOutstandingâ Performance: The image processing workflow continues to be optimized, helping to reduce build and page load times.
- More Details: Image processing algorithms are improved, and bandwidth optimization techniques are enhanced.
-
âTighteningâ Security with Remote Images: Handling images from external sources (remote images) is given more security focus. We need to explicitly configure the allowed domains to avoid potential security risks.
remotePatterns
Configuration:
// next.config.js module.exports = { images: { remotePatterns: [ { protocol: "https", hostname: "example.com", pathname: "/account123/**", }, ], }, };
More Detail: priority
- The âGolden Keyâ to Improving LCP
Largest Contentful Paint (LCP) is one of the important Core Web Vitals, measuring the time it takes for the largest content element on a page to become visible. Using the priority
property appropriately for important images can make a big difference in improving LCP, providing a better user experience and helping the website âscore pointsâ with search engines. đ
Code Example: Using the priority
Property
import Image from "next/image";
import logo from "../public/logo.png";
function Header() {
return (
<header>
<Image
src={logo}
alt="Company Logo"
width={100}
height={50}
priority // The logo is usually an important element that needs to load early
/>
{/* ... other header components */}
</header>
);
}
export default Header;
Next.js 15 (2024): A âSmootherâ Development Experience with More New Features đ
This latest version, Next.js 15, continues to âpleaseâ developers by bringing improvements focused on the experience and adding more useful features for next/image
.
You are absolutely right! This section can be presented more accurately and in more detail. Below is the adjusted version:
Notable Features in Next.js 15
Next.js 15 continues to bring useful improvements to next/image
, focusing on enhancing user experience and providing more flexible configuration options.
âblurâ Placeholder - Smoother Image Loading with a Blurry Effect:
The âblurâ placeholder feature allows displaying a blurred version of the image before the original image is fully loaded. This is a technique that improves perceived performance, creating the impression of faster and smoother page loading in the userâs eyes. Instead of a blank space or a plain background color, users will see a preview of the image, reducing the feeling of waiting and creating continuity in the experience.
-
How It Works: When
placeholder="blur"
is used, Next.js will generate a very small and blurred version of the image (usually a small base64 image) and display it as a placeholder. When the original image is loaded, the blurred placeholder is smoothly replaced. -
Usage for Static and Remote Images:
- Static Images (Local Images): For images imported directly from the
public
orapp
directory, Next.js can automatically generate theblurDataURL
during the build process. This makes usingplaceholder="blur"
very simple. - Remote Images: For images from external sources, you need to provide a value for the
blurDataURL
property. You can createblurDataURL
in several ways:- Using supporting libraries: There are libraries like
plaiceholder
that can help generateblurDataURL
from the imageâs URL. - Creating it manually: You can download the remote image, resize it to a very small size, and convert it into a base64 string.
- Using supporting libraries: There are libraries like
- Static Images (Local Images): For images imported directly from the
-
Usage Example:
import Image from "next/image";
import myImage from "../public/my-image.jpg";
function BlurredImage() {
return (
<Image
src={myImage}
alt="Illustration Image"
width={500}
height={300}
placeholder="blur"
// For static images, Next.js can automatically generate blurDataURL
/>
);
}
function BlurredRemoteImage() {
return (
<Image
src="https://example.com/remote-image.jpg"
alt="Remote Image"
width={500}
height={300}
placeholder="blur"
blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkqAcAAIUAgUW0RjgAAAAASUVORK5CYII=" // Example blurDataURL
/>
);
}
export default BlurredImage;
Note: Creating and managing blurDataURL
for remote images can be a bit more complex, but it allows you to take advantage of the âblurâ placeholder effect even with images from external sources.
More Flexible remotePatterns
Configuration for Better Security and Control:
Next.js 15 expands the configuration capabilities of remotePatterns
, allowing you to define more detailed patterns for the URLs of remote images. This provides greater flexibility and control over the origin of images, while enhancing the security of the application.
-
Benefits of Detailed Configuration:
- Enhanced security: You can explicitly specify the allowed hostnames, ports, and pathnames, preventing the loading of images from unwanted or potentially harmful sources.
- Better control: Suitable for applications with many different image sources with specific security requirements. For example, you can have different patterns for product images, user avatars, etc.
-
Detailed Configuration Example:
// next.config.js
module.exports = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "assets.example.com", // Only allow from this hostname
port: "",
pathname: "/product-images/**", // Only allow from this path
},
{
protocol: "https",
hostname: "cdn.users.com", // Another hostname
port: "8080", // Only allow on port 8080
pathname: "/avatars/**",
},
],
},
};
In the example above, we have configured to only allow loading images from https://assets.example.com/product-images/**
and https://cdn.users.com:8080/avatars/**
. Any attempts to load images from other sources will be blocked, helping to protect your application.
Improved Development Experience:
Next.js 15 continues its efforts to provide a better development experience for next/image
users. Although there are no specific âmajorâ features announced in the release notes related to the development experience of next/image
itself, general improvements in build performance, debugging capabilities, and other development tools in Next.js 15 will also indirectly benefit working with this component. This includes better error handling, clearer notifications, and a smoother workflow.
Outstanding Benefits When Using next/image
Through continuous development and improvement, next/image
has proven its role as a powerful tool that brings many practical benefits to managing and displaying images in Next.js applications. Below are the outstanding advantages that next/image
offers:
-
Comprehensive Performance Optimization:
next/image
is not just a ârefurbishedâ<img>
tag, but a comprehensive image optimization solution.- Reduced Page Load Time: By automatically optimizing images during the build process, creating appropriately sized versions, and using modern image formats like WebP and AVIF (when configured),
next/image
significantly reduces image file sizes, thereby reducing page load times. The lazy loading mechanism also plays an important role, only loading the images that are actually needed when the user scrolls to the display area, helping the website load faster on the first visit. - Improved User Experience: Faster page load times translate to a smoother and more positive user experience. Users wonât have to wait long to see images, especially on mobile devices or when the network connection is unstable.
- Enhanced SEO Effectiveness: Page loading speed is an important factor in ranking websites on search engines. Using
next/image
helps improve page load speed, which can provide an SEO advantage.
- Reduced Page Load Time: By automatically optimizing images during the build process, creating appropriately sized versions, and using modern image formats like WebP and AVIF (when configured),
-
Easy and Effective Responsive Image Support: Displaying images that fit the userâs screen size is crucial to ensuring the best experience.
- Automatically Generate Appropriate Image Sizes: When you provide the
width
andheight
attributes,next/image
can automatically generate multiple sizes of the image during the build process. srcset
andsizes
Attributes: Combined with thelayout="responsive"
orlayout="fill"
attributes,next/image
automatically generates thesrcset
andsizes
attributes for the<img>
tag, allowing the browser to choose the most appropriate image version based on the screen size and resolution of the device. This helps save bandwidth and ensures images are displayed sharply on all devices.
- Automatically Generate Appropriate Image Sizes: When you provide the
-
Complete Elimination of CLS (Cumulative Layout Shift) Issues: CLS is one of the annoying factors for users when browsing the web.
- Ensuring Stable Display Space: By requiring the declaration of
width
andheight
(or usinglayout="fill"
),next/image
helps the browser determine the necessary space for the image in advance, thereby preventing the layout from âjumpingâ when the image is fully loaded. This contributes to improving user experience and Core Web Vitals scores.
- Ensuring Stable Display Space: By requiring the declaration of
-
Enhanced Security When Using Remote Images: Displaying images from external sources poses potential security risks.
remotePatterns
Configuration:next/image
provides aremotePatterns
mechanism in thenext.config.js
file, allowing you to clearly specify the domains and paths from which images are allowed to be loaded. This helps prevent loading images from untrusted sources, minimizing the risk of attacks or malicious code injection.
-
Seamless Integration and Optimization with the Next.js Ecosystem:
next/image
is specifically designed to work smoothly within the Next.js environment.- Works Effectively with App Router and Pages Router: Whether you are using the App Router or Pages Router,
next/image
works well and provides appropriate features. - Easy to Use and Configure: The
next/image
API is designed to be simple and easy to use. The configuration options innext.config.js
are also very flexible, allowing you to customize according to your projectâs needs. - Benefits from Other Next.js Features:
next/image
leverages the available features of Next.js, such as the image optimization API, which helps the image optimization process take place automatically and efficiently.
- Works Effectively with App Router and Pages Router: Whether you are using the App Router or Pages Router,
In summary, next/image
not only helps optimize image display performance but also brings many other benefits in terms of user experience, SEO, and security, while integrating perfectly into the Next.js ecosystem, becoming an indispensable tool for Next.js developers.
The âSilent Warriorâ: The Power of CDN Alongside next/image
đ
Up to this point, you and I have clearly seen the powerful âtechniquesâ that next/image
brings to image optimization. But for those âhigh-qualityâ images to reach users worldwide as quickly as possible, we need the support of another âsilent heroâ: CDN (Content Delivery Network).
Imagine a CDN as a high-speed âtransfer stationâ system for your web content. Instead of all images âresidingâ on a single origin server, the CDN will create copies of them and place them on various servers around the world. When a user accesses your website, the CDN will automatically âchooseâ the server closest to them to âdeliverâ the images, helping to:
- Increase page load speed âtremendouslyâ: Images load faster because the âdistanceâ is shorter. This is especially important for users far from your origin server.
- Reduce the load on the âsilent heroâ - the origin server: When the CDN âshouldersâ some of the image distribution work, your origin server will operate more âlightly,â especially when there is a lot of traffic.
- Ensure a âsmoothâ experience even during traffic âstormsâ: CDNs are highly scalable, helping your website operate stably even when a large number of users access it simultaneously.
So, how do next/image
and CDN âwork togetherâ?
In fact, next/image
and CDN are a perfect âpair.â next/image
handles âprocessingâ images into the most optimized versions (appropriate size, modern format), while the CDN handles âtransportingâ those âdishesâ to users as quickly as possible.
When using next/image
, we can configure it to work âharmoniouslyâ with our CDN. For example, you can use dedicated CDN services like Cloudinary, Imgix, or even configure Next.js to use a CDN for static images in the public
directory.
In short, if next/image
is the âtalented chefâ who helps you have quality images, then the CDN is the âsuper-fast delivery systemâ that helps those images reach your customers quickly and efficiently. Donât forget this âsilent heroâ on your journey to optimize website performance! đ
Comparison Table: The Development Journey of next/image
Feature | Next.js 10 (2020) | Next.js 11 (2021) | Next.js 12 (2021) | Next.js 13 (2022) | Next.js 14 (2023) | Next.js 15 (2024) |
---|---|---|---|---|---|---|
Optimization | Automatic on build | Automatic on build | Optimized build perf | Automatic on build | Further optimized | Further optimized |
Lazy Loading | Yes | Improved | Yes | Yes | Yes | Yes |
Size Optimization | Yes | More accurate calc | Yes | Yes | Yes | Yes |
Format Support | WebP, AVIF (config) | Better AVIF support | WebP, AVIF (config) | WebP, AVIF (config) | WebP, AVIF (config) | WebP, AVIF (config) |
App Router | Not supported | Not supported | Not supported | Supported | Supported | Supported |
âfillâ Layout | No | No | No | Yes | Yes | Yes |
sizes Property | No | No | No | Yes | Yes | Yes |
priority Property | No | No | No | No | Yes | Yes |
âblurâ Placeholder | No | No | No | No | No | Yes |
Optimization âPlaygroundsâ for Every Type of Project đŻ
For each different type of web project, next/image
will provide appropriate optimization solutions:
- E-commerce Projects: Manage thousands, even tens of thousands of product images with large sizes. Using
next/image
significantly reduces storage space and increases page load speed, providing a better shopping experience for customers. - Blog or Online Magazine Projects: Supporting responsive images helps display images optimally on all devices, with image sizes automatically adjusted to fit the screen size.
- Business/Brand Website Projects: Use the
priority
attribute for logos and main banner images to improve initial page load times, create a good impression with users, and improve SEO scores. - Websites Emphasizing Security: Configure
remotePatterns
to clearly specify the external image sources that the system allows, maximizing security.
Troubleshooting Common Errors When Using next/image
đ ď¸
Although powerful and convenient, using next/image
can sometimes encounter a few issues. Here are some common errors and how to fix them:
-
âFailed to Optimize Imageâ Error: Usually occurs when working with remote images without configuring
remotePatterns
correctly.Solution: Ensure that the domains containing the images you want to use are listed in the
remotePatterns
configuration in thenext.config.js
file.// next.config.js module.exports = { images: { remotePatterns: [ { protocol: "https", hostname: "your-image-domain.com", }, ], }, };
-
Cannot Use New Features on Older Next.js Versions: Some new attributes and features are only available on recent Next.js versions.
Solution: Update Next.js to the latest version to be able to fully use the latest features of
next/image
. -
Images Not Displaying at the Desired Size: Often happens when you forget to declare the
width
andheight
attributes for the image.Solution: Always ensure you provide
width
andheight
when usingnext/image
to avoid CLS and ensure the image displays at the correct size.<Image src="/image.png" alt="Example Image" width={500} height={300} />
-
Difficulty Managing âblurâ Placeholders for Remote Images: Creating
blurDataURL
for images from external sources can be challenging.Solution: You can use tools or libraries that support creating
blurDataURL
from images, for example, using an online base64 encoder or integrating image processing libraries into your build process.
âDissectingâ the Operating Mechanism of next/image
đ
To better understand how next/image
works âbehind the scenes,â letâs examine the main technical steps:
-
Using the Image Optimization API: During the build process, Next.js automatically optimizes images using the Image Optimization API. This API will create multiple versions of the same image with different sizes and formats.
-
Lazy Loading âWhen Necessaryâ: When a user scrolls the page close to the image display area,
next/image
will automatically load that image, helping to improve initial page load performance and save bandwidth.
- âSmartâ Responsive Optimization: The browser will automatically select the most appropriate image version based on the userâs screen size and resolution.
Sharing From Personal Experience: âThe First Step is Always the Hardestâ With next/image
đŻ
In 2021, when I started getting acquainted with Next.js and the next/image
component, my first project was a news website. The requirement to display many images with all sorts of sizes and complex layouts made image optimization one of the top priorities.
At that time, figuring out how to make images display sharply on all devices while not affecting page load speed was a real challenge. I remember very clearly the difficulties of having to âmeasure and weighâ each image size, and then fumbling around trying to configure next.config.js
so that the application could work with images from external sources.
Configuring remotePatterns
in next.config.js
is a prime example. For next/image
to be able to optimize images from CDNs or cloud storage platforms, accurately declaring the protocol
, hostname
, and pathname
is extremely important. I remember âfumbling aroundâ for a while, trying all sorts of configurations that just wouldnât work. The âFailed to optimize imageâ error kept popping up and âannoyingâ me. To configure next/image
to optimize images from a CDN with the hostname cdn.example.com
and the images located in the /images/
directory, I configured next.config.js
as follows:
// next.config.js
module.exports = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "cdn.example.com",
pathname: "/images/**",
},
],
},
};
It took me quite a bit of time to get used to and configure this part correctly. Fortunately, at that time, thanks to the help and keyword suggestions from an experienced colleague (at a time when AI wasnât as prevalent as it is now), I gradually âunraveledâ this problem. The feeling of âbreakthroughâ when the configuration finally ran correctly was indescribable!
That was one of my first and most important lessons with next/image
. It shows that, in addition to the powerful optimization features that this component brings, mastering the configuration options is key to us being able to fully exploit its potential and avoid unnecessary âbitter fruits.â This lesson also reminded me that, in the development process, sharing and learning from the community is extremely important.
Conclusion: Mastering next/image
, Elevating Your Front-end Skills đ
Throughout its exciting development journey from its early beginnings (Next.js 10) to the latest version (Next.js 15), next/image
has been continuously upgraded and perfected. From the initial foundational features such as automatic optimization and lazy loading, to unique improvements such as the âfillâ layout and âblurâ placeholder, next/image
has affirmed its position as an indispensable tool for optimizing and managing images for Next.js projects.
Hopefully, through this âlengthyâ article, you and I have together âunveiled the secretsâ and gained a better understanding of next/image
and the important improvements it has undergone through each development milestone of Next.js. Feel free to apply this knowledge to your real-world projects to create websites that are not only âsmoothâ in performance but also âimpressiveâ visually. I believe that mastering next/image
will be an important step on your journey to conquering the peaks of your front-end development skills. I wish you much success and continued passion on your journey to âtransformâ ideas into reality through front-end! đŞ