Horje
How To Create A Custom Image Loader In NextJS?

Next.js includes a robust image component with built-in performance enhancements. However, there may be situations when you want a bespoke image loader to handle certain image hosting services or loading behaviour. This article will walk you through the steps of constructing a custom image loader in Next.js, from project setup to demonstration and output.

Steps to Create Cusom Image Loader in Next JS

Step 1: Setting Up a New Next.js Project

create a next.js project in your preferred location with running the following command in the terminal.

npx create-next-app imgloaderdemo
projectsetup

choose options as shown

Step2 : Navigate into the project directory

using following command navigate to project directory or simple open from vs code open folder option inside file available top left side.

cd imgloaderdemo

Step 3: Project Structure

We will create a custom loader component in the index.js file and we will use that custom loader to load our image.

do

imgloaderdemo project structure

The updated dependencies in package.json file:

 "dependencies": {
"next": "14.2.3",
"react": "^18",
"react-dom": "^18",
}

Step 4: Custom Image Loader Function

  • Next.js lets you define your own image loader function. This function accepts an object with parameters src, width, and quality and returns a URL string.
  • Make a new component for your customized loader. In the index file , and lets call it customLoader.
  • In this example, replace https://example.com/ with the base URL of your image hosting service. The loader constructs a URL that includes width and quality parameters.

Step 5: Integrate the Custom Loader

  • lets use this custom loader in our next.js application as following.
  • Here, we use the customLoader function and provide it to the Image component’s loader prop. The src attribute should be relative to the base URL set in your loader function.

Step 6: Configuring next.config.mjs

  • If you are fetching images from an external source, make sure your Next.js configuration allows external images. Modify the next.config.mjs:
  • Replace ‘firebasestorage.googleapis.com’ with the domain of your image hosting service.
JavaScript
//src/pages/index.js
import Image from "next/image";

const customLoader = ({
    src,
    width,
    quality,
}) => {
    return `https://firebasestorage.googleapis.com
        /v0/b/shaikclone.appspot.com/o/
        ${src}?alt=media&token=ca82acf3-426d-4cf1-872f-
        5575eac7de55&w=${width}&q=${ quality || 75 }`;
};

export default function Home() {
    return (
        <div style={{ height: "100vh" }}>
            <h1>Custom Image Loader Demo</h1>
            <Image
                loader={customLoader}
                src="gfglogo.jpg"
                alt="Sample Image"
                width={500}
                height={300}
            />
        </div>
    );
}
JavaScript
// next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
    reactStrictMode: true,
    images: {
        domains: [
            "firebasestorage.googleapis.com",
        ], 
        //replace with your actual one for demonstration firebase is used.
    },
};

export default nextConfig;

Step 7: Running the Application

Run your Next.js application to see the custom image loader in action:

npm run dev

Step 8: Testing the Custom Image Loader

Open your browser and go to http://localhost:3000. Your image should be loaded with the specified width and quality criteria set by your custom loader.

verifyloadedimg

verify this image should be loaded.

Step 9: Inspecting the Image URL

Inspect the image URL to ensure it matches the structure given in your own loader function.

HTML
<img
    src=
"https://firebasestorage.googleapis.com/v0/b/shaikc…n=ca82acf3-426d-4cf1-872f-5575eac7de55&w=640&q=75"
    alt="Sample Image"
    width="500"
    height="300"
/>

The URL should include the width (w=500) and quality (q=75) parameters set in the customLoader function.

Note: The usage of Image in newest version of react throws an warning of fetchPrioriy, although it works fine. If you want to avoid error being logged The only solution found for this is to roll back in react version that is 18.2.0. hoping for a fix from react newer upcoming version.

warn

fetchpriority error

Conclusion

Creating a custom image loader in Next.js enables you to interface with many image hosting services and tailor image loading behavior to your specific requirements. Using this approach, you can create a Next.js project, construct a custom image loader, and see it in action. This guarantees that your photos load efficiently and match your individual needs.




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
How To Create React Multiple File Upload Using NextJS And Typescript? How To Create React Multiple File Upload Using NextJS And Typescript?
How To Set Up Mongoose With Typescript In NextJS ? How To Set Up Mongoose With Typescript In NextJS ?
How To Use React Context In NextJS With Typescript? How To Use React Context In NextJS With Typescript?
How To Implement Optimistic Updates in Redux Applications? How To Implement Optimistic Updates in Redux Applications?
What Are Some Common Performance Bottlenecks in React-Redux Applications? What Are Some Common Performance Bottlenecks in React-Redux Applications?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18