Open In App

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:

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=
                width={400}
                height={100}
                alt="GeeksForGeeks Logo"
                placeholder="empty"
                priority={true}
            />
 
            <br />
 
            <h4>img tag:</h4>
            <img
                src=
                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)


Article Tags :