Open In App

Next.js Static File Serving

Last Updated : 05 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

NextJs is an awesome React-based framework that provides a developer everything required for production-grade applications along with awesome built-in features, customizations, and easy to develop environment.

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.

Add static file in Next.js: To add static files, Next Js has provided us with the “public” folder. This is the folder where we need to keep all our static files.

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.

Create NextJS Application: You can create a new Next.js project using the below command:

npx create-next-app my-awesome-app

Project Structure: It will look like this.

Directory structure of our awesome app

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.

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.

Output of our above code

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads