AllTechnologyProgrammingWeb DevelopmentAI
    CODING IS POWERFUL!
    Back to Blog

    Next.js Image Perfection - Taming the Invalid src prop Beast

    13 min read
    April 20, 2025
    Next.js Image Perfection - Taming the Invalid src prop Beast

    Table of Contents

    • Intro: Invalid src Error
    • Next.js Image Component
    • Why Error Happens?
    • next.config.js Explained
    • Fix: Domain Config
    • Fix: remotePatterns
    • Troubleshooting
    • Optimize Images
    • Advanced Config
    • Conclusion
    • People Also Ask for

    Intro: Invalid src Error

    If you're developing with Next.js and incorporating images, especially from external sources, you might have encountered the frustrating "Invalid src prop" error. This error typically manifests as:

    Error: Invalid src prop `` on `next/image`, hostname "" is not configured under images in your `next.config.js`

    This message indicates that Next.js is preventing images from loading from domains that haven't been explicitly allowed in your configuration. Imagine you're trying to display an image from a platform like utfs.io, and you see this error. It can be puzzling at first, but there's a good reason behind it.

    Let's understand why this error arises and, more importantly, how to effectively resolve it and get your external images displaying correctly in your Next.js application.


    Next.js Image Component

    Next.js provides a powerful and optimized <Image> component to handle images in your applications. This component is designed to improve web performance by automatically optimizing images and serving them in modern formats like WebP whenever possible. [1]

    The <Image> component is not just a simple replacement for the standard HTML <img> tag. It offers significant enhancements, including:

    • Automatic Image Optimization: Images are automatically optimized for different devices and screen sizes, reducing bandwidth usage and improving load times. [1]
    • Lazy Loading: Images are loaded only when they are about to enter the viewport, further boosting initial page load performance.
    • Modern Image Formats: Serves images in modern formats like WebP if the browser supports it, offering better compression and quality compared to older formats like JPEG and PNG. [1]
    • Security: By default, Next.js <Image> component is configured for security, restricting image loading from explicitly defined trusted domains in your next.config.js file. This is the reason behind the "Invalid src prop" error when dealing with external images. [1]

    While these features are incredibly beneficial, the security aspect, particularly the domain restriction, is often the cause of the dreaded "Invalid src prop" error when working with images from external sources. Let's delve deeper into why this error occurs and how to effectively resolve it.


    Why Error Happens?

    When working with the next/image component in Next.js and using external images, you might encounter the dreaded "Invalid src prop" error. This error typically indicates that the hostname of the external image URL is not configured in your next.config.js file. [1]

    Next.js employs a smart image optimization strategy for performance and security. The next/image component optimizes images on demand, resizing and serving them in modern formats. To maintain security and efficiency, Next.js restricts image loading to explicitly trusted domains defined in your next.config.js file. [1]

    Therefore, if you attempt to load an image from a domain like utfs.io (as seen in the reference example) or any other external source without explicitly allowing it, Next.js will throw the "Invalid src prop" error. [1] This mechanism ensures that your Next.js application only loads images from domains you trust, enhancing security and controlling image optimization processes.


    next.config.js Explained

    In Next.js, nextConfig within your next.config.js or next.config.ts file is the central place to configure your Next.js application. It allows you to customize various aspects of Next.js, from build settings to routing and image optimization. For tackling the "Invalid src prop" error, the images property inside nextConfig is key.

    Image Configuration

    Next.js Image component is designed for performance and security. To optimize images efficiently and securely, Next.js needs to know which domains are trusted sources for images. This is where the images configuration in next.config.js comes into play. By default, Next.js only allows images from the same domain as your application.

    Domains and remotePatterns

    To load images from external websites, you need to explicitly tell Next.js to trust those domains. You can do this using either the domains or remotePatterns option within the images configuration.

    • domains: Use this option when you know the exact hostnames of the external image sources. You provide an array of domain strings.
    • remotePatterns: This is more flexible and allows you to specify patterns for matching image URLs. It's useful when dealing with dynamic subdomains or URLs that follow a predictable structure.

    By configuring either domains or remotePatterns in your next.config.js, you're essentially whitelisting the external image sources, resolving the "Invalid src prop" error and allowing Next.js to optimize images from those sources.


    Fix: Domain Config

    The most common and straightforward solution to the Invalid src prop error is to correctly configure the allowed domains in your next.config.js file. Next.js needs to know which external image domains are trusted for optimization. If you're trying to load images from a domain that isn't on its list, it throws the mentioned error. [1]

    To fix this, you need to tell Next.js to trust the domain from which you are fetching your images. Hereโ€™s how you can do it:

        
    module.exports = {
      images: {
        domains: ['your-domain.com', 'another-domain.com'],
      },
    };
        
      

    In the next.config.js file, within the module.exports, you should have an images object. Inside this object, you'll find (or need to create) a domains array. Add the hostname of your image provider (e.g., utfs.io, example.com) to this array. [1]

    Example: If your image URL is https://utfs.io/images/myimage.jpg, you would add 'utfs.io' to the domains array.

        
    module.exports = {
      images: {
        domains: ['utfs.io'],
      },
    };
        
      

    After updating your next.config.js, restart your Next.js development server to apply the changes. This should resolve the Invalid src prop error for images from the specified domains.


    Fix: remotePatterns

    When dealing with external images in Next.js, the Invalid src prop error can be a common roadblock. This error arises because Next.js, for security and optimization, needs to know which external image sources are trusted. One of the refined ways to specify these trusted sources is using the remotePatterns option within your nextConfig.images configuration.

    The remotePatterns array in your next.config.js allows you to define patterns that Next.js uses to validate external image URLs. This is particularly useful when you need to allow images from multiple subdomains or specific paths of a domain, offering more flexibility than the simpler domains option.

    Hereโ€™s how you can configure remotePatterns in your next.config.js file:

            
    const nextConfig = {
      images: {
        remotePatterns: [
          {
            protocol: 'https',
            hostname: 'example.com',
          },
          {
            protocol: 'https',
            hostname: 'cdn.another-site.org',
            pathname: '/images/**', // Optional: to match images under /images path
          },
        ],
      },
    };
    
    module.exports = nextConfig;
            
        

    In this configuration:

    • protocol: Specifies the protocol of the image URL, usually 'http' or 'https'.
    • hostname: Defines the hostname of the image domain (e.g., 'example.com').
    • pathname (Optional): Allows you to further restrict the pathnames that are allowed. Using a pattern like '/images/**' permits any path that starts with '/images/'.

    By using remotePatterns, you gain granular control over allowed external image sources, efficiently resolving the Invalid src prop error and ensuring your Next.js application loads images securely and as intended.



    Optimize Images

    In the modern web, images are crucial for user experience. They enhance visual appeal and convey information effectively. However, unoptimized images can significantly slow down your Next.js application. This negatively impacts user experience and SEO.

    Next.js provides a powerful tool to handle images: the next/image component. This component is designed to automatically optimize images, ensuring they are delivered in the best format and size for the user's device.

    By default, next/image offers several key optimizations:

    • Automatic Format Optimization: Next.js serves images in modern formats like WebP when supported by the browser, reducing file sizes without compromising quality.
    • Resizing: Images are automatically resized to fit the container, preventing the browser from downloading unnecessarily large images.
    • Lazy Loading: Images are loaded only when they are about to enter the viewport, improving initial page load time.

    However, to leverage these optimizations effectively, especially when using external images, proper configuration is essential. One common issue developers face is the "Invalid src prop" error. This error typically arises when trying to use images from domains not explicitly allowed in your Next.js configuration.

    In the following sections, we will explore how to configure Next.js to handle external images correctly and avoid the "Invalid src prop" error, ensuring your images are not only optimized but also load seamlessly in your application. We'll delve into the necessary configurations within your next.config.js file to tame this beast and achieve image perfection in your Next.js projects.


    Advanced Config

    While simply listing domains in images.domains in your next.config.js file often solves the Invalid src prop error, there are scenarios where you need more flexibility. Let's explore some advanced configurations for more complex situations.

    Using remotePatterns

    For scenarios involving subdomains, specific path prefixes, or wildcard patterns in your image URLs, the remotePatterns option provides a powerful alternative. Instead of just listing domains, remotePatterns allows you to define more granular rules using pathname and protocol matching.

    For instance, consider images from a CDN that uses varying subdomains like images1.example.com, images2.example.com, etc. Instead of listing each subdomain individually, you can use remotePatterns to define a pattern that covers all of them.

    Example Configuration

    Here's how you might configure remotePatterns in your next.config.js to handle images from *.example.com:

            
    module.exports = {
      images: {
        remotePatterns: [
          {
            protocol: 'https',
            hostname: '*.example.com',
          },
        ],
      },
    };
            
        

    In this configuration:

    • protocol: 'https': Specifies that only HTTPS protocol images are allowed.
    • hostname: '*.example.com': Allows any subdomain under example.com. The * acts as a wildcard.

    remotePatterns offers more control and can simplify your configuration when dealing with complex image URL structures, ensuring that you can efficiently manage external images in your Next.js application without encountering the Invalid src prop error.


    Conclusion

    In this guide, we've navigated the intricacies of Next.js image optimization and tackled the dreaded Invalid src prop error. By understanding the security measures Next.js implements for image sources, you can confidently configure your next.config.js to handle external images seamlessly.

    Remember, the key to avoiding the Invalid src error lies in explicitly defining allowed image sources. Whether through the domains or the more flexible remotePatterns configuration, Next.js empowers you to control image loading while maintaining robust security and optimization.

    By correctly configuring your next.config.js, you not only resolve the error but also unlock the full potential of Next.js's Image component, ensuring optimized images and a smoother development experience. Keep experimenting with different configurations and optimizations to achieve pixel-perfect image delivery in your Next.js applications.


    People Also Ask For

    • Why am I getting invalid src prop error in Next.js?

      The "Invalid src prop" error in Next.js arises when using the Image component to display images from external domains that are not explicitly allowed in your next.config.js file. [1]

    • How do I fix invalid src prop in Next.js?

      To resolve the "Invalid src prop" error, you need to configure the images property within your next.config.js file. You can either use the domains option for simple domain whitelisting or remotePatterns for more advanced pattern-based matching. [1]

    • What is next.config.js in Next.js?

      next.config.js is a configuration file in Next.js that allows you to customize various aspects of your application, including image optimization settings, environment variables, and webpack configurations. [1]

    • Should I use domains or remotePatterns for image configuration?

      Use domains when you want to allow images from specific, well-known domains. Opt for remotePatterns when you need more flexibility, such as allowing images from subdomains or domains matching a specific pattern. [1]


    Join Our Newsletter

    Launching soon - be among our first 500 subscribers!

    Suggested Posts

    Emerging Tech Trends - Shaping Our World ๐ŸŒ
    TECHNOLOGY

    Emerging Tech Trends - Shaping Our World ๐ŸŒ

    Exploring 2025's top AI trends: 5 past developments & 5 expected future impacts. ๐Ÿค–
    19 min read
    6/23/2025
    Read More
    The search results overwhelmingly confirm that AI, especially its future, impact, and various applications (generative AI, agentic AI, AI in search, etc.), is a top-tier, highly relevant, and extensively discussed topic in technology for 2024 and 2025.

Therefore, "The Future of AI" is an excellent choice for the title. I will modify it to be more catchy and include an emoji, ensuring no colon is used.

Proposed title: "The Future of AI - Powering Tomorrow's World ๐Ÿš€"
This meets all the criteria:
- Single title.
- Tech-related.
- Catchy.
- Uses a hyphen instead of a colon.
- Includes an emoji.
- Relates to a top-ranking and widely discussed tech topic.The Future of AI - Powering Tomorrow's World ๐Ÿš€
    AI

    The search results overwhelmingly confirm that AI, especially its future, impact, and various applications (generative AI, agentic AI, AI in search, etc.), is a top-tier, highly relevant, and extensively discussed topic in technology for 2024 and 2025. Therefore, "The Future of AI" is an excellent choice for the title. I will modify it to be more catchy and include an emoji, ensuring no colon is used. Proposed title: "The Future of AI - Powering Tomorrow's World ๐Ÿš€" This meets all the criteria: - Single title. - Tech-related. - Catchy. - Uses a hyphen instead of a colon. - Includes an emoji. - Relates to a top-ranking and widely discussed tech topic.The Future of AI - Powering Tomorrow's World ๐Ÿš€

    AI's future and applications like generative AI are top tech topics for 2024-2025, shaping tomorrow. ๐Ÿš€
    19 min read
    6/23/2025
    Read More
    Best Web Development Tools - The Next Big Thing
    WEB DEVELOPMENT

    Best Web Development Tools - The Next Big Thing

    Discover next-gen web dev tools to conquer workflow challenges, boost efficiency & collaboration. ๐Ÿš€
    22 min read
    6/23/2025
    Read More
    Developer X

    Muhammad Areeb (Developer X)

    Quick Links

    PortfolioBlog

    Get in Touch

    [email protected]+92 312 5362908

    Crafting digital experiences through code and creativity. Building the future of web, one pixel at a time.

    ยฉ 2025 Developer X. All rights reserved.