How to fix the image not loading issue in Nextjs?

Tahera AlamTahera Alam
2 min read

Table of contents

I recently started learning nextjs and in my very first project I wanted to use some images but they were not loading even after giving the correct file paths. I cross-checked the paths, and they were all correct but still, I had the issue where my image wouldn't show up.

If you are also facing the same issue, here's how you can fix it.

  1. Instead of importing images and linking them like the following, directly link them in the image's src attribute.

     //this won't work
     import { btcLogo } from "../public/btc.svg";
     <img src={btcLogo}/>
    

    When attempting to import images in Next.js, using an import statement to directly import the image file won't work. Next.js does not support importing image files in this manner.

    Instead, add your images to the public folder and link them in the image's src attribute like this:

     <img src="/btc.svg" />
    

Notice how we didn't add ../public in the src. This is because in Next.js, when referencing assets from the public directory, you need to omit the /public part in the URL. The public directory is already considered the root directory for static assets.

By removing /public from the src attribute, Next.js will correctly resolve the URL path to the image located in the public directory.

And it works! Congrats!


I always loved those short sweet blogs which fixed my issues quickly. I hope my very first blog on this platform could solve yours. Thanks for reading this!

Until next time, happy coding!

0
Subscribe to my newsletter

Read articles from Tahera Alam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tahera Alam
Tahera Alam

I'm a front-end developer who loves developing seamless web experiences. I make frontend web apps, MERN stack web apps, and write blogs.