Next.js File Conventions: page.js
Last Updated :
14 Aug, 2024
Next.js File Conventions are practices and rules for organizing files in a Next.js application to manage routing and components efficiently. In these conventions, the page.js file represents a specific route in the application, where each file in the pages or app directory corresponds to a route.
This convention helps in defining page-level components and their rendering logic, supporting both server-side and client-side rendering.
Page.js File
In Next.js, page.js files are used to define the content and layout of individual pages in your application. Each page.js file corresponds to a route in your application, with its location in the src/app directory reflecting the route structure. This file typically exports a React component that renders the page content. Next.js uses this file to handle server-side rendering, static site generation, or client-side rendering based on your configuration and data fetching methods.
Syntax
const HomePage = () => (
<div>
<h1>Welcome to the Home Page</h1>
</div>
);
export default HomePage;
Dynamic Routing and Parameters
The page.js file can manage dynamic routes and parameters.
Example: In a file like app/blog/[slug]/page.tsx, you can use TypeScript to define the route and handle dynamic segments.
export default function DynamicPage({
params,
searchParams,
}: {
params: { slug: string },
searchParams: { [key: string]: string | string[] | undefined }
}) {
return <h1>Dynamic Content for {params.slug}</h1>;
}
Steps to Implement page File Convention in Next JS
Step 1: Create a Next.js application using the following command.
npx create-next-app@latest gfg
Step 2: It will ask you some questions, so choose as the following.
SetupStep 3: After creating your project folder i.e. gfg, move to it using the following command.
cd gfg
Folder Structure
Project StructureDependencies
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.5"
}
we are using a page.js file in a Next.js application to create a dynamic home page with interactive features. The page includes a green h1 heading and an h3 heading for context. It also features a button that, when clicked, updates the displayed text using React's useState hook. The use client directive is used to enable client-side functionality in this component.
Example: The below example demonstrates the use of File Conventions: page.js.
JavaScript
// src/app/page.js
"use client";
import React, { useState } from 'react';
const HomePage = () => {
const [text, setText] = useState("Click the button to change this text.");
const handleClick = () => {
setText("Text has been changed!");
};
return (
<div style={{ padding: '20px' }}>
<h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
<h3>Next.js File Conventions: page.js</h3>
<p>{text}</p>
<button onClick={handleClick} style={{ padding: '10px', fontSize: '16px' }}>
Change Text
</button>
</div>
);
};
export default HomePage;
To run the Application open the terminal in the project folder and enter the following command:
npm run dev
Output
Next.js File Conventions: page.jsRendering Behavior of page.js
Next.js offers various ways to render pages. The `page.js` file handles Client-Side Rendering (CSR) by updating content in the browser, Server-Side Rendering (SSR) by generating pages on the server for each request, and Static Site Generation (SSG) by pre-rendering pages at build time for faster loading.
Client-Side Rendering (CSR)
- How page.js Handles CSR: In CSR, the page is rendered in the browser with JavaScript. After the initial HTML loads, the rest of the page updates and data are managed on the client side. This method is ideal for pages that need real-time interactions and dynamic updates.
- Transitioning Between Pages: Next.js ensures smooth client-side navigation without reloading the entire page. Its internal routing system updates the page content dynamically as you navigate through different sections.
Server-Side Rendering (SSR)
- SSR with page.js: With SSR, Next.js generates the HTML for your page on the server for each request, ensuring that the page is always up-to-date when it reaches the user. You can enable SSR in page.js using the getServerSideProps function.
- When to Use SSR vs. CSR: Use SSR when you need the page to show the latest data or want the content rendered on the server before it reaches the user. Use CSR for pages that are less reliant on real-time data or where client-side interactions are more crucial.
Static Site Generation (SSG)
SSG generates the page's HTML at build time rather than request time. By using getStaticProps, you fetch data and create static pages that are served quickly to users. This approach is best for pages with content that doesn’t change often.
Benefits of SSG:
- Faster Load Times: Static pages are served quickly from a CDN, leading to faster page loads.
- Less Server Load: Pre-built pages reduce the server's workload during runtime.
- Better SEO: Pre-rendered pages are fully visible to search engines, enhancing your site's SEO.
Key Points to remember
- File Location: The location of the page.js file determines its route. For example, src/app/about/page.js corresponds to the /about route.
- Component Export: Each page.js file should export a React component.
- Rendering: Next.js uses the page.js file to determine how to render the page, whether server-side, statically, or client-side.
Similar Reads
File Conventions in Next.js
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
5 min read
Next JS File Conventions: error.js
Next.js manages file conventions to perform error handling within your application. By using error.js, you can define how your application responds to errors at the page or application level. This file allows you to create custom error pages that handle exceptions gracefully and provide users with a
4 min read
Next.js File Conventions: layout.js
In Next.js, the layout.js file is a key component in the app directory, allowing developers to create shared UI elements that persist across multiple routes. This feature is part of the Next.js App Router, introduced to improve the organization and efficiency of React applications. Purpose of layout
4 min read
Next JS File Conventions: default.js
Default.js is a very important file in Next.js projects, serving as a default entry point of the project. Also, while using Next.js, sometimes you soft navigate (move between pages without fully reloading the page). In that case, Next.js keeps track of the pages you were on. However, In case of hard
4 min read
Next JS File Conventions: middleware.js
In Next.js, the middleware.js file is one powerful tool to add custom functionality through the request/response cycle of the application. It is able to run some code before finalizing a request, which may involve actions such as authentication, logging, or even rewriting of URLs. Middleware can be
7 min read
Next.js next.config.js File
The next.config.js file in a Next.js application is a configuration file used to customize and extend the behavior of Next.js. It allows developers to adjust various settings such as routing, environment variables, image optimization, and more to tailor the application to their specific needs. What
3 min read
page.js in Next JS
In Next.js, page.js is a file commonly used to define individual pages of your application. Each page is a React component that represents a route in your application. The page.js file is crucial for routing and rendering content in your Next.js project.In this article, we will see about the pages a
4 min read
CSS Naming Conventions
CSS is foundational in web design, offering control over page appearance and interaction. While effective for style management, it's less ideal for complex projects, leading to the need for CSS naming conventions. These standards enhance stylesheet efficiency and organization, aiding team navigation
3 min read
What is Link component in Next.js ?
In Next.js, Link is used to create links between pages in a Next.js app. To create a link, insert the <Link> component into your page, and specify the path to the page you want to link to. Â Link ComponentThe Link component in Next.js is a built-in feature that provides client-side navigation
2 min read
template.js in Next JS
In Next.js, the template.js file can serve various purposes depending on the context and project requirements. It can be used to create reusable templates for components, pages, or even configuration settings. Utilizing a template.js file helps to maintain a consistent structure and reduce repetitiv
4 min read