N Kaushik

How to load image from a local folder in Nextjs

July 01, 2021

How to load image from a local folder in Nextjs:

In Nextjs, we can load images from a static folder. If you don’t want to use any third party services like S3, you can put your images in a static folder and Image component will load it from here.

public folder:

Nextjs uses public folder for static assets. public folder is placed at the root level of a Nextjs project. If we place any image in this folder, we can access that image by using the base url.

For example, if we add one image user.png in the public folder, we can access it as like below:

<Image src="/user.png" alt="user profile image" width="100" height="100" />

Other usages of public folder:

public folder can be used as the root folder in a Nextjs website. We can use this folder for robots.txt, favicon.ico, and other static files like google domain verification file etc.

Conflicting file names:

All items in the public folder should have unique names. It shouldn’t be same as any file in the pages folder.

Runtime file addition:

We can’t add any files to this folder at runtime. All files should be included during build time. Otherwise, it will not work.

Using a different directory:

We can’t use any other directory for public assets. Also we can’t rename this directory. Otherwise, it will not work.

Conclusion:

public directory is an important directory in Nextjs. Make sure to optimize your images and assets before adding them to this directory as these are included in the build time.

If you love this post, please subscribe to my newsletter :)


Subscribe to my Newsletter

© 2021, nkaushik