How To Add/Serve Static Files From A Next.js Application?

In this tutorial, we will see how to serve static files from a Next.js application. It’s a very easy process and Next.js provides us a built in way to get this done. We can add our static files like images, zip files, sitemap, PDF files, downloadable, music file in a /public directory. Files inside the public or static directory will be publicly hosted in the root of the folder can be addressed in our code by using the URL of the website (Eg. https://codingiseasy.com/sitemap.xml). Here for the example, we have added sitemap.xml inside the public or static directory of the Next.JS Application.

Whatever is not going to change like Images, pdf and all other kinds of static files are supported to be inside /public (for newer version of Nexr.JS) or /static folder (for older version of Next.JS) in this framework.

In case, you can’t find the public folder or static folder in your application then first you have to create a /public folder (on the root folder) in your project and make sure you enter the correct spelling, else that will return you an error. Also you should not have any same named files in your /pages directory. All these will not fetch you the desired result.

In older versions of Next.js, we used to add files like images inside the /static directory instead of /public directory. Hence make sure that you are using the latest versions and if you are using the older one, then change the directory’s name as /static.

Add any static file into your directory. For example, it can be an image.png, a pdf or anything else. It’s up to you what you want to add.

Adding & Calling Images from Public Folder in Next.JS

Directory (newer Version of Next JS)

/public 

Directory (older Version of Next JS)

/static

Code

<img src="/image.png" alt="Coding Is Easy - Next JS" />

This small piece of code will display the image that we have added into our public directory as ‘image.png’ file. Any .xml, .txt, .html file can be added to the public directory. It’s the same as we do in any other stacks like React JS, Node.js Framework etc.

Hope you have understood how to serve static files in a Next.js Application. Hit the comment section if you have any doubts.

Thank you
Happy learning.

Leave a Comment