Open In App

File Conventions in Next.js

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Next.js file conventions include specific directories and filenames like pages, app, layout.js, and middleware.js, which automatically define routes, layouts, middleware, and other configurations, ensuring a structured and efficient project organization.

In this article, we will learn about the different different file conventions provided by next.js.

NextJS File Conventions

NextJS provides a file structure convention that simplifies the development process of your applications. These file conventions help you to handle errors and define the structure of your application. It provides default.js, error.js, not-found.js, layout.js, loading.js, page.js, route.js, middleware.js, etc. to manage your applications easily.

File NameLocationPurpose
default.jsapp/Provides default layout or component structure for pages.
error.jsapp/Custom error page to handle application-wide errors.
instrumentation.jsapp/Used for tracking and monitoring purposes, such as logging and analytics.
layout.jsapp/Defines the common layout structure (header, footer, etc.) for pages.
loading.jsapp/Displays a loading state while the page or data is being fetched.
middleware.jsapp/Custom middleware to handle requests and responses, often for authentication.
not-found.jsapp/Custom 404 page to handle not found errors.
page.jspages/Represents individual pages in the application, automatically routed.
route.jsapp/Defines custom server-side routing logic.
Route Segment Configapp/Configuration for route segments, such as dynamic routes.
template.jsapp/Defines reusable templates for specific types of content or pages.
Metadata FilesConfiguration and metadata for the application, such as manifest.json.

default.js

default.js file is a fallback page that is rendered when NextJS cannot determine which page to render. It happens when a user refreshes the page or navigates to a URL that does not match any of the defined routes. It is a React component or a function that returns a React component.

const DefaultLayout = ({ children }) => (
<div>
<Header />
{children}
<Footer />
</div>
);

export default DefaultLayout;

error.js

error.js file defines an error UI boundary for a route segment. It is useful for catching unexpected errors that occur in Server Components and Client Components and displaying a fallback UI.

const ErrorPage = () => (
<div>
<h1>Something went wrong</h1>
</div>
);

export default ErrorPage;

layout.js

layout.js is a React component that is shared between multiple pages in an application. It allows us to define a common structure and a same appearance for a group of pages. It should accept and use a children prop. During rendering, children will be populated with the route segments the layout is wrapping.

const Layout = ({ children }) => (
<div>
<Header />
<Sidebar />
<main>{children}</main>
<Footer />
</div>
);

export default Layout;

loading.js

loading.js file is typically designed to be displayed during page transitions when content is being fetched from the server. If the content is already present in cache memory, such as when a user revisits a page they’ve previously loaded, the loader may not be displayed since there is no need to fetch data from the server.

const Loading = () => (
<div>
<p>Loading...</p>
</div>
);

export default Loading;

middleware.js

middleware.js that has access to request, response objects and the next middleware function. It allows you to intercept and manipulate requests and responses before they reach route handlers.

export function middleware(req, res, next) {
console.log('Request:', req.url);
next();
}

not-found.js

not-found.js file renders a custom user interface (UI) when the notFound function is called within a route segment. When user enters a wrong route path, this not-found.js file will be automatically displayed.

const NotFound = () => (
<div>
<h1>Page Not Found</h1>
</div>
);

export default NotFound;

page.js

page.js is a react component that is used to create a UI for each routes within specific route directory.

const HomePage = () => (
<div>
<h1>Welcome to the Home Page</h1>
</div>
);

export default HomePage;

route.js

Defines custom routing logic, allowing for more advanced route handling beyond default page-based routing.

export function customRouteHandler(req, res) {
if (req.url === '/special-route') {
res.end('This is a custom route');
} else {
res.end('Default route');
}
}

Steps to Create NextJS Application:

Step 1: Create a NextJS application using the following command.

npx create-next-app@latest gfg

Step 2: It will ask you some questions, so choose as the following.

√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? (recommended) ... Yes
√ Would you like to customize the default import alias (@/*)? ... No

Step 3: After creating your project folder i.e. gfg, move to it using the following command.

cd gfg

Project Structure:

nextjs-file-conventions

Example: The below example demonstrates the use not-found.js, page.js, layout.js File Conventions in Next.js.

JavaScript
//File path: src/app/page.js

export default function Home() {
    return (
        <>
            <h1>Home Page</h1>
        </>
    );
}
JavaScript
//File path: src/app/layout.js
'use client'
import { useRouter } from 'next/navigation'

export default function RootLayout({ children }) {
    const router = useRouter()

    return (
        <html lang='en'>
            <body>
                <h1 style={{ color: 'green' }}>
                    GeeksForGeeks | Next.js File Conventions{' '}
                </h1>
                <ul>
                    <li style={{ cursor: 'pointer' }} onClick={() => router.push('/')}>
                        Home
                    </li>
                    <li
                        style={{ cursor: 'pointer' }}
                        onClick={() => router.push('/about')}
                    >
                        About
                    </li>
                    <li
                        style={{ cursor: 'pointer' }}
                        onClick={() => router.push('/profile')}
                    >
                        Profile
                    </li>
                </ul>
                <hr />
                {children}
            </body>
        </html>
    )
}
JavaScript
//File path: src/app/not-found.js

export default function Page() {
    return (
        <>
            <h1>This page Does not exist</h1>
            <p>
                If a specific route is not created, Next.js will automatically serve the
                `not-found.js` file.
            </p>
        </>
    )
}
JavaScript
//File path: src/app/about/page.js

export default function Page() {
    return (
        <>
            <h1>About Page</h1>
        </>
    );
}

Start your application using the command:

npm run dev

Output:

File-Convention

Conclustion

File conventions in Next.js, such as pages, app, layout.js, and middleware.js, streamline project organization by automatically defining routes, layouts, and configurations. This structured approach enhances code maintainability and development efficiency in Next.js applications.


Next Article

Similar Reads