Open In App

Next.js getInitialProps

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

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.

PropertyDescriptionAvailability
pathnameCurrent route, the path of the page in /pagesBoth
queryQuery string of the URL, parsed as an objectBoth
asPathString of the actual path (including the query) shown in the browserBoth
reqHTTP request objectServer only
resHTTP response objectServer only
errError object if any error is encountered during the renderingBoth

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:

p1-ezgifcom-optimize

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:

file

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.


Next Article

Similar Reads