Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
How to Load NextJS Images from an External URL ?
Next article icon

How To Create A Custom Image Loader In NextJS?

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a custom image loader in Next.js allows you to control how images are loaded and optimized. This is useful for integrating with different image services or handling specific image processing needs. Here’s how to create and use a custom image loader: This article will walk you through the steps of creating a custom image loader in Next.js, from project setup to demonstration and output.

Approach

To create a custom image loader in Next.js, define a loader function to format image URLs. Pass this function to the loader prop of the <Image> component. Optionally, use environment variables for dynamic URL configurations.

Steps to Create Custom Image Loader in Next JS

Step 1: Setting Up a New Next.js Project

Initialize a next.js project in your preferred location by running the following command in the terminal.

npx create-next-app imgloaderdemo
projectsetup
choose options as shown

Step 2: 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 the 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.


Next Article
How to Load NextJS Images from an External URL ?

F

firoz21bj772
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Next.js
  • Next.js - Questions

Similar Reads

  • How to Load NextJS Images from an External URL ?
    In Next.js, loading external URL images is important because it allows developers to incorporate dynamic content and enrich user experiences by displaying images from various sources seamlessly within their applications. In this article, we will explore two different approaches to loading NextJS Ima
    3 min read
  • How to create a Custom Error Page in Next.js ?
    Creating a custom error page in Next.js allows you to provide a better user experience by customizing the appearance and messaging of error pages like 404 and 500. In this post we are going to create a custom error page or a custom 404 page in a Next JS website. What is a custom error page?The 404 p
    2 min read
  • How to add Image Carousel in Next.js ?
    In this article, we are going to learn how we can add an Image Carousel in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. ApproachTo create image carousel in next.js we are going to use a react-r
    2 min read
  • How to create Image Slider in ReactJS ?
    Image Slider is a dynamic web element that displays a collection of images and has a slider to switch between the Images. It is the most common feature to show image collection in web applications or mobile apps. Websites like Amazon.com, Flipkart.com, and many e-commerce sites use image sliders to
    4 min read
  • How to Load Data from a File in Next.js?
    Loading Data from files consists of using client-side techniques to read and process files in a Next.js application. In this article, we will explore a practical demonstration of Load Data from a File in Next.js. We will load a validated CSV input file and display its contents in tabular format. App
    3 min read
  • How to Create Random Image in React Native ?
    React Native has gained widespread popularity for its ability to create cross-platform applications using a single codebase. One interesting feature you might want to implement is displaying random images within your app. Whether you're building a gallery app or simply adding an element of surprise,
    2 min read
  • How to Add a Background Image in Next.js?
    Next.js is a powerful React framework that allows for server-side rendering and the generation of static websites. Adding a background image to your Next.js application can enhance the visual appeal of your web pages. This article will guide you through the process of adding a background image to a
    3 min read
  • How to Create a Next.js form ?
    Forms are an essential part of many web applications, allowing users to input data and interact with the website. Next.js, with its powerful features for building server-rendered React applications, provides an ideal platform for creating forms. In this article, we'll explore step-by-step how to cre
    4 min read
  • How to check an image is loaded or not in VueJS ?
    While inserting an Image in a VueJS project, it may fail to load due to the following reasons: Writing wrong image URL.Due to poor connection Approach: We are going to use an event in <img> to check whether an image is loaded or not in VueJS, the event we are going to use is: @load: The @load
    3 min read
  • How to Add Custom Local Fonts in Next.js ?
    Adding custom fonts in Next.js project enhances the typography. It also improves the performance as the fonts are loaded directly from project assets. They can be integrated by importing font files into a project, defining @font-face rules in CSS, and applying them across components for consistent s
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences