File Conventions in Next.js
Last Updated :
23 Jul, 2025
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 Name | Location | Purpose |
---|
default.js | app/ | Provides default layout or component structure for pages. |
error.js | app/ | Custom error page to handle application-wide errors. |
instrumentation.js | app/ | Used for tracking and monitoring purposes, such as logging and analytics. |
layout.js | app/ | Defines the common layout structure (header, footer, etc.) for pages. |
loading.js | app/ | Displays a loading state while the page or data is being fetched. |
middleware.js | app/ | Custom middleware to handle requests and responses, often for authentication. |
not-found.js | app/ | Custom 404 page to handle not found errors. |
page.js | pages/ | Represents individual pages in the application, automatically routed. |
route.js | app/ | Defines custom server-side routing logic. |
Route Segment Config | app/ | Configuration for route segments, such as dynamic routes. |
template.js | app/ | Defines reusable templates for specific types of content or pages. |
Metadata Files | | Configuration 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:

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:

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.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects