getInitialProps is a special function provided by Next.js that runs on the server side before rendering a page. This function allows you to fetch data from an external API, database, or any other data source, and pass it as props to your React components. By doing so, you can pre-populate your pages with data and make them more SEO-friendly, as search engines can crawl your pages' content easily. In this article, we will explore one of its features, getInitialProps, by building a small app.
Next.js getInitialProps
getInitialProps is a lifecycle method in Next.js that allows you to asynchronously fetch data and pass it to your page or component as props before rendering. It can be used in both pages and custom App components, making it versatile for server-side data fetching.
getInitialProps is an async function that returns an object containing the props that will be passed to your components.
Note: The getInitialProps API is deprecated. Insted the recommanded APIS are getStaticProps or getServerSideProps.
Syntax:
The getInitialProps method is a static async function that is defined in a page component (e.g., pages/index.js). It takes a single argument context, which is an object that contains information about the request (on the server) or the client's router (on the client). The getInitialProps function should return an object with the props that should be passed to the page component.
const Page = ({ prop }) => (
<div>{prop}</div>
);
Page.getInitialProps = async (ctx) => {
const res = await fetch('https://api...com');
const json = await res.json();
return { prop: json.data };
};
export default Page;
Parameters:
It receives only one argument called context which is an object with the following properties.
Property | Description | Availability |
---|
pathname | Current route, the path of the page in /pages | Both |
query | Query string of the URL, parsed as an object | Both |
asPath | String of the actual path (including the query) shown in the browser | Both |
req | HTTP request object | Server only |
res | HTTP response object | Server only |
err | Error object if any error is encountered during the rendering | Both |
Note: getInitialProps is a static method, so it's defined as a property of the Page component instead of a method within it. This method is automatically called by Next.js when the page is loaded and it populates the props of the component before rendering it
Working
- Server-Side Rendering (SSR): When a page is accessed directly (e.g., via a URL), getInitialProps runs on the server, allowing you to fetch data before the HTML is generated and sent to the client.
- Client-Side Navigation: When navigating between pages using Next.js's Link component or other client-side methods, getInitialProps runs on the client, providing data without a full page reload.
Steps to Create Next.js App
Step 1: To get started, we need to create a new Next.js app. Open your terminal and run the following command:
npx create-next-app next-app
This will create a new Next.js app in a directory named next-app
Step 2: Navigate to the project directory:
cd next-app
Project Structure:
Example 1: Fetching data from an API; Next, we will create a new page that displays the list of users.
Create a new file named users.js inside the pages directory with the following code:
JavaScript
// Filename - pages/users.js
const Users = ({ users }) => {
return (
<div>
<h1>Users</h1>
<ul>
{users.map(user => (
<li key={user.login.uuid}>
<img src={user.picture.thumbnail}
alt={user.name.first} />
<span>{user.name.first} {user.name.last}</span>
</li>
))}
</ul>
</div>
)
}
Users.getInitialProps = async () => {
const res = await fetch('https://.../api/?results=10')
const data = await res.json()
return { users: data.results }
}
export default Users;
In this code, we have created a new functional component named Users that receives the users prop and displays it as a list. We have also defined the getInitialProps method that fetches the data from the Random User API and returns it as the users prop.
Run the app: Now, run the app by running the following command in your terminal:
npm run dev
This will start the development server and open your app in your default browser at http://localhost:3000/users.
You should now see a list of 10 random users fetched from the API.
Output:
Example 2: Passing query parameters: Next.js provides a way to pass query parameters to a page using the URL. We can use getInitialProps to retrieve these query parameters and pass them as props to our page component. For example, suppose we have a Post page that displays a single post based on its id. We can pass the post id as a query parameter in the URL and use getInitialProps to retrieve it and fetch the corresponding post.
Create a new file post.js in the pages directory with the following code::
JavaScript
// pages/post.js
const Post = ({ post }) => (
<div>
<h1>{post.id}</h1>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
Post.getInitialProps = async ({ query }) => {
const { id } = query;
const res = await fetch(`https://...com/posts/${id}`);
const post = await res.json();
return { post };
};
export default Post;
Output:
In this example, we have a post page that displays a single post based on its id. The post id is passed as a query parameter in the URL (e.g., /post?id=1), and getInitialProps retrieves it from the query object. It then uses the fetch function to fetch the corresponding post from the JSONPlaceholder API and returns it as an object with a post property. This post object is then passed as props to the post component, which displays the post title and body.
Conclusion
In conclusion, the getInitialProps method in Next.js is a powerful feature that allows you to fetch data on the server side and pass it as props to your React components. This helps to improve the initial load time of your application, which is crucial for providing a good user experience.
Similar Reads
Next.js getStaticProps() Function
Data fetching in NextJS: To fetch the data from our own backend or using third-party APIs, we generally use client-side fetching using the fetch API provided by the browser. It fetches the data from the client-side on every request or browser reload. Â But NextJS provides us with better ways to fetch
3 min read
Next.js ESLint
ESLint is a widely-used tool for identifying and fixing problems in JavaScript code. In Next.js projects, integrating ESLint helps ensure code quality and consistency by enforcing coding standards and catching errors early in the development process.In this article, we'll explore how to set up ESLin
3 min read
Next.js Headers
Next.js is a React framework that is used to build full-stack web applications. It is used both for front-end as well and back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is the Header function. In this article, we will learn a
2 min read
Next.js getServerSideProps() Function
The getServerSideProps method is used to fetch data and pre-render the page. It enables server-side rendering. As a result, it's particularly useful for sites with dynamic data or requests that must be made often, such as retrieving authorized user data.Syntax:export async function getServerSideProp
3 min read
Next.js Function Fetch
Next.js is a React framework that enhances UI development with built-in features like server-side rendering and static site generation. It supports data fetching both on the server and client sides, enabling developers to load and manage data efficiently. By utilizing functions like fetch, Next.js a
6 min read
Functions in Next JS
Next.js provides a suite of functions and hooks that enhance server-side rendering, static generation, routing, and more. These functions are essential for managing data fetching, handling requests, and optimizing performance in Next.js applications.Next.js FunctionsNext.js functions simplify server
4 min read
Next.js Client Components
Next.js, a popular React framework, has seen significant growth in recent years due to its robust features for building modern web applications. One of the key concepts introduced in Next.js is the distinction between Server and Client Components. In this article, we'll focus on Client Components an
4 min read
Next.js getStaticPaths() Function
The getStaticPaths() function in NextJS is used to pre-generate static pages for dynamic routes.For example, we can create a page that has dynamic parameters like `user/[ID]` Â and then we can create a static version for every possible value of the dynamic parameter. In our case, if the dynamic param
3 min read
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 d
5 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