Categories
Blog Javascript Learning

Solution: TypeError: Failed to construct ‘URL’: Invalid URL

Hello,

If you are facing error :


Unhandled Runtime Error
TypeError: Failed to construct 'URL': Invalid URL
Failed to construct ‘URL’ : Invalid URL in your nextjs app

And you already have following loader ‘imgix’ settings in your next.config.js file

images: {
    // loader and path setting for android build to load nextjsimage and also on web on certain scenarios!
    loader: 'imgix',
    path: '/', // Remove the path prefix for production images
    domains: [
      'xxx.com',
      '*.xxx.com',
      'aaa.xxx.com',
      'via.placeholder.com',
    ],
}

To fix this the solution provided here worked out well!

Code snippet solution: source page stackoverflow

const loaderProp =({ src }) => {
    return src;
}

<Image
      src={currentImage.imageurl}
      alt={currentImage.imageurl} 
      layout="fill"
      className={styles.imageSize} 
      loader={loaderProp}
/>

we just need to add loader prop to the Image tag of next.js component and passdown the callback function which resolves the error above, voila!

Hope this also help you if you are facing this solution in your next.js application.

happy learning!

Categories
Javascript Learning Tech

How to fix nextjs appending http://localhost:3000/_next/image? to the image srcset how to remove for production build for images?

Hello,

Welcome to the question and for the search, facing this issue? lets quickly see how we can fix this, with and in next.config.js file.

In Next.js, when using the next/image component, the src attribute is automatically transformed to a URL that goes through the Next.js image optimization pipeline. During development, this URL may include http://localhost:3000/_next/image? to indicate the local development server.

However, for production images, you can configure Next.js to remove the http://localhost:3000/_next/image? prefix. Here’s how you can achieve that:

Create a custom loader for Next.js images:

  • Open next.config.js and add the following code:
    • module.exports = {
    • images: {
      • loader: 'imgix',
      • path: '', // Remove the path prefix for production images
    • }, };
  • This configuration sets the loader option to use the imgix loader, which removes the http://localhost:3000/_next/image? prefix. The path option is set to an empty string, this will leave the prefix for image urls and left blank

Now you can easily build your project and test to images are loading fine with absolute url path if applied so.

Hope this help to solve the issue.

Happy Learning!