Next.js Static File Serving
Next.js allows you to serve static files from the public
directory, making them accessible at the root URL. This feature enables easy inclusion of assets like images, fonts, and static HTML files, enhancing your application's functionality and user experience.
Static files
All those files which need to be served by the application to the user like images, static HTML files, static js files, favicon, SVGs, robots.txt, etc are static files. These files remain static or the same and needed to be served to the general user as it is.
Approach
To serve static files in Next.js, place them in the public
directory. This is the folder where we need to keep all our static files. Access these files in your components using the /
prefix. This method supports images, fonts, and other assets, enhancing your application's functionality and user experience.
Syntax:
Save the file in public directory
/public
/ images
/dummyimage.png
Use the file in required component
// Use the Image
<Image src="/images/dummyimage.png" width = {400} />
Note: Static files can only be kept in the public folder. No other folder could serve static files in NextJs. We can reference these static files through our code starting from the base URL "/".
In this post, we are going to take a look at Static File Serving in NextJs.
Steps to Create NextJS Application
You can create a new Next.js project using the below command:
npx create-next-app my-awesome-app
Project Structure:

Example: If there is an image file named geeksforgeeks.png in our public folder then we can refer it using /geeksforgeeks.png in our code.
// pages/index.js
import Image from "next/image";
import styles from "../styles/Home.module.css";
export default function Home() {
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>
My Awesome Next App
</h1>
<Image src="/geeksforgeeks.png" width={500} height={100} />
</main>
</div>
);
}
Step to run the application: Now start the application by running the following command.
npm start
Output: Similarly, you can serve other static files as well.

Note: Make sure that no file in the "public" directory has the same name as a file in the "pages" directory as that can cause an error.
Reference: https://nextjs.org/docs/basic-features/static-file-serving