Next JS Image Optimization: Best Practices for Faster Loading
Large and unoptimized images can impact a website's performance on loading time. Optimizing images is necessary to improve the performance of the website. Next.js provides built-in support for image optimization to automate the process, providing a balance between image quality and loading speed.
Prerequisites:
Next JS provides a built-in next/image component for optimizing images. It provides features such as automatic resizing, lazy loading, support for various image formats, and many more. It converts jpg, and png file format into a WebP format. WebP is a modern image format that provides lossless and lossy compression for web images. It allows websites to display high-quality images with much smaller file sizes than traditional formats like PNG and JPEG.
To use this component, import it from the next/image.
import Image from 'next/image';
Props supported by Image Components
Property | Description | Values |
---|---|---|
src | Takes a path string. Can be an absolute external URL or an internal path. External URLs must be added to remotePatterns in next.config.js . | Path string (URL or internal) |
width | Takes a width in pixels. Helps render a placeholder of the correct size and prevent layout shifts when the actual image loads. | Pixels |
height | Takes a height in pixels. Helps render a placeholder of the correct size and prevent layout shifts when the actual image loads. | Pixels |
alt | Takes text. Used by search engines and displayed if the image is not found. | Text |
layout | Provides layout for the image. | intrinsic, responsive, fixed |
priority | Ensures that images are prioritized during page loading. | true, false |
placeholder | Enhances perceived loading speed and provides a better user experience. | - |
quality | Defines the quality of the image. Takes a value between 1 and 100. Default is 75. | 1 to 100 (default 75) |
Best Practices for Faster Loading Images
Use the Next.js Image Component: Utilize the built-in <Image> component provided by Next.js, which automatically optimizes images for better performance. This component supports features like lazy loading, resizing, and format selection.
Specify Image Dimensions: Always define the width and height attributes for your images. This practice helps the browser allocate the correct space before the image loads, preventing layout shifts and enhancing page performance.
Optimize Image Quality: Adjust the image quality to balance between visual quality and file size. Reducing the quality for less critical images can significantly decrease load times, improving the overall speed of your site.
Use Layout Options: Choose the appropriate layout option (intrinsic, responsive, or fixed) based on your design needs. The responsive layout is especially useful for images that need to adjust to various screen sizes, ensuring they fit well on different devices.
Prioritize Critical Images: Set high-priority attributes for images essential to the initial page load, such as hero images or key visuals. Prioritizing these images ensures they load quickly, improving the initial load time of your page.
Utilize the Placeholder Attribute: Enhance the perceived loading speed by using the placeholder attribute. This feature provides a blurred or empty placeholder while the image loads, offering a smoother user experience.
Creating Next.js Application
Step 1: Create a Next.js application using the following command.
npx create-next-app@latest gfg
Step 2: After creating your project folder i.e. gfg, move to it using the following command.
cd gfg
Project Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.1.0"
},
"devDependencies": {
"autoprefixer": "^10.0.1",
"postcss": "^8",
"tailwindcss": "^3.3.0",
"eslint": "^8",
"eslint-config-next": "14.1.0"
}
Example: The below example demonstrates the use of Image Optimization.
Note: Remove the included css file from layout.js file.
//File path: src/app/page.js
import Image from "next/image";
export default function Home() {
return (
<>
<h4>Image component:</h4>
<Image
src=
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210420155809/gfg-new-logo.png"
width={400}
height={100}
alt="GeeksForGeeks Logo"
placeholder="empty"
priority={true}
/>
<br />
<h4>img tag:</h4>
<img
src=
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210420155809/gfg-new-logo.png"
alt="GeeksForGeeks Logo" />
</>
);
}
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'media.geeksforgeeks.org',
port: '',
pathname:
'/wp-content/cdn-uploads/20210420155809/gfg-new-logo.png',
},
],
},
};
export default nextConfig;
To run the Application open the terminal in the project folder and enter the following command:
npm run dev
Output:
Here, you can see the actual image size and file type is 6.9kb(png) and the optimized image side and file type is 3.5kb(webp)
Conclusion
Optimizing images in Next.js ensures faster load times and better user experience. Use the <Image> component, define dimensions, optimize quality, choose the right layout, prioritize critical images, and use placeholders. These practices prevent layout shifts, reduce load times, and enhance your website's performance and visual appeal.