How do you serve static files from a Next.js application?

Luckily, the Next.js framework provides a built-in way to do this through the /public directory.

Any file inside the /public directory (placed in the root of your project folder) can be referenced by your code starting at the base URL for your website ("/"). All types of static files are supported, such as images, text, pdf, etc.

If you don't already have a /public directory in your project, go ahead and create one in the root of your Next.js website folder:

    
      mkdir public
    
  

Then, add an image or other type of static file to the new /public directory (i.e. image.png). In your code, you'll be able to access the image or other type of static file like this:

    
      <img src="/image.png" alt="Alt tag for your image." />
    
  

This code will display the image you've added to the /public directory.

The /public directory can be useful for other files like the sitemap.xml, robots.txt, and any other static files (including .html).

There you have it! That's how you serve static files from your Next.js application.

Thanks for reading and happy coding!