Open In App

Next.js getInitialProps

Last Updated : 22 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Next.js is a popular React-based framework that simplifies server-side rendering (SSR) of web applications. With its powerful features, it has become the go-to choice for building modern web applications. In this article, we will explore one of its features, getInitialProps, by building a small app.

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.

getInitialProps is an async function that returns an object containing the props that will be passed to your components.

 

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;

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

Create a new 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




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




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.

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads