Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use Nextjs GetInitialProps to Fetch Data

Next.js is a popular React-based framework that provides both client-side and server-side rendering and other features to build modern web applications. One of the key features of Next.js is the Nextjs getInitialProps (now legacy API) method, which allows developers to fetch data on the server side and pre-render the resulting data.

In this article, we will explore the getInitialProps method in Next.js and its use cases. Additionally, we will examine the differences between Nextjs getInitialProps and two other data-fetching methods, namely getServerSideProps and getStaticProps, to provide a clearer understanding of their unique functionalities and when to utilize each method in your projects.

Setting Up a Next.js App

We’ll need a Next.js app to test out each of these methods. To set up a Next.js app, you can use the create-next-app command-line tool, which creates a new Next.js project with all the necessary files and dependencies.

npx create-next-app my-app

Select the following options from the terminal’s prompts:

✔ Would you like to use TypeScript? … No / Yes

✔ Would you like to use ESLint? … No / Yes

✔ Would you like to use Tailwind CSS? … No / Yes

✔ Would you like to use src/ directory? … No / Yes

✔ Would you like to use App Router? (recommended) … No / Yes

✔ Would you like to customize the default import alias (@/)? … No / Yes

✔ What import alias would you like configured? … @/

After completing the setup process, navigate to the newly created folder by executing the following command:

cd my-app

To start your server, run the following command:

yarn dev

Upon successfully starting the server, it will be accessible on port http://localhost:3000 or any available port on your computer.

At this point, your screen should display a webpage similar to the one shown below:

Next, open up the directory in your preferred code editor. If you’re using Visual Studio Code (VSCode), you can easily open the folder by entering the command below in your terminal:

code .

Create a new components folder in the pages folder, then create a new Nav.tsx file inside the components folder with the following code:

import Link from "next/link";
import { usePathname } from "next/navigation";
import React from "react";

export const Nav = () => {
  const pathname = usePathname();
  console.log(pathname);
  return (
    <nav className='flex gap-2 text-blue-700'>
      <Link
        className={`hover:underline ${
          pathname == "/user" ? "underline font-semibold" : ""
        }`}
        href='/user'
      >
        User
      </Link>
      <Link
        className={`hover:underline ${
          pathname == "/" ? "underline font-semibold" : ""
        }`}
        href='/'
      >
        Posts
      </Link>
      <Link
        className={`hover:underline ${
          pathname == "/comments" ? "underline font-semibold" : ""
        }`}
        href='/comments'
      >
        Comments
      </Link>
    </nav>
  );
};

We’ll utilize this NextJS project and navbar to showcase examples later in this article.

What is the Nextjs getInitialProps Function?

The getInitialProps function is an async lifecycle method in Next.js that runs on the server during the initial request for a page component such as pages/index.js.

The Nextjs getInitialProps function is executed before the rendering of the React component, allowing you to fetch data from APIs, make database queries, or perform other computations to populate the page with dynamic content.

It takes a single argument called context, which is an object with several properties, including res, req, pathname, query, aspath, and err. The getInitialProps function should return an object with the props that should be passed to the page component.

// Page function component example
const Page = ({ prop }) => (
  <div>{prop}</div>
);

Page.getInitialProps = async (ctx) => {
// Fetch your data here
  const res = await fetch('https://api.example.com');
  const json = await res.json();
  return { prop: json.data }; // pass the response data as a prop to the Page function component
};

export default Page;

The getInitialProps method enables fetching data from various sources, such as external APIs or databases, improving initial load time and enhancing user experience.

Nextjs getInitialProps Use cases

getInitialProps is particularly useful for scenarios where you need to fetch data that is dynamic and depends on the current page or user.

Here are some common use cases:

  • Fetching user data: Retrieve user profile information, authentication status, or saved preferences.

  • Loading content based on pathname: Fetch specific content based on the requested page, such as blog posts, product details, or user-specific pages.

  • Integrating with APIs: Make API calls to external services to fetch data for the current page.

  • Improved SEO: Pre-rendering SEO metadata and Open Graph tags on the server ensures that search engines see the complete webpage with accurate information, potentially boosting your page’s ranking.

  • Faster initial load: By fetching and injecting SEO data on the server, you avoid client-side JavaScript calls for this information, speeding up the initial page load for users.

The getInitialProps Context Parameter Table

The Nextjs getInitialProps method receives several context parameters that provide valuable information about the current page request:

Here’s a table summarizing the context parameters available in the Nextjs getInitialProps method:

NameDescription
resThe HTTP response object. An instance of the ServerResponse class.
reqThe HTTP request object. An instance of the IncomingMessage class.
pathnameThe path of the page in /pages. The requested path, excluding the query string.
queryThe query string of the URL; parsed as an object. An object containing the URL query string parameters.
aspathThe actual path (including the query) shown in the browser. The full URL path, including the query string.
errAn error object if an error occurred during rendering or request processing.

Cons of getInitialProps Method

Despite its usefulness, Nextjs getInitialProps has a few limitations:

ConceptExplanation
Performance overheadRepeatedly fetching data on each request can increase server load and impact performance.
Potential for race conditionsIf multiple clients request the same page simultaneously, there may be race conditions during data fetching.
Increased complexityAdding a getInitialProps method can make your components more complex and less maintainable.

Additionally, getInitialProps is a legacy API as mentioned earlier, and Next.js recommends using getStaticProps or getServerSideProps instead.

Let’s take a look at an example of how to fetch a post comment data using the getInitialProps function in a Next.js application.

Create a new comments.tsx file and update it with the following TypeScript code.

import { NextPageContext } from "next";
import { Nav } from "./components/Nav";

type Comments = {
  id: string;
  name: string;
  body: string;
  email: string;
}[];

Page.getInitialProps = async (ctx: NextPageContext) => {
  const res = await fetch(
    "https://jsonplaceholder.typicode.com/posts/1/comments"
  );
  const comments = await res.json();
  console.log(comments);
  return { comments };
};

export default function Page({ comments }: { comments: Comments }) {
  return (
    <main className='flex flex-col gap-5 bg-white min-h-screen text-slate-700 p-10'>
      <Nav />
      <h3 className='text-xl text-slate-700 font-bold'>Comments</h3>
      {comments.map(({ id, name, email, body }) => {
        return (
          <article key={id}>
            <h2 className='font-bold text-xl'>{name}</h2>
            <p>{body}</p>
            <span className='text-slate-500 text-sm'>Email: {email}</span>
          </article>
        );
      })}
    </main>
  );
}

Visit http://localhost:3000/comments or /comments on your running server port and the above code will produce the following output:

The console.log(comments) will only appear on the terminal and not the console at first load, but when you navigate from comments page to another, and back to the comments page, you’ll start seeing the output from the log.

We can mimic this client navigation by clicking the comment link again as demonstrated below:

Give Purecode AI a try today to instantly generate thousands of customizable, styled Bootstrap and JavaScript components to accelerate your web development projects.

What is the difference between getInitialProps and getServerSideProps props

The getServerSideProps props and getInitialProps both fetch data on the server-side and pre-render the resulting data. However, there are some key differences between the two.

ConceptGetServerSidePropsGetInitialProps
Execution TiminggetServerSideProps is executed on every server request. getServerSideProps is designed for fetching dynamic data that varies per request.while getInitialProps is invoked only on the initial request for a page (including client navigation). getInitialProps focuses on fetching static data that remains consistent for all users accessing the same page.
Data Fetching ScopegetServerSideProps is primarily used to fetch data that is specific to the current user or request, such as user profile information, authentication status, or personalized content.getInitialProps is more suited for fetching data that is shared across all users, such as blog posts, product listings, or common configuration settings.
Performance OptimizationgetServerSideProps is commonly employed to improve the initial load time of a page by fetching dynamic data on the server and injecting it into the pre-rendered HTML.getInitialProps, on the other hand, plays a role in optimizing SEO by generating static HTML pages with embedded data, making your content more readily indexable by search engines.

In summary, getServerSideProps is ideal for handling dynamic data-driven requests, while Nextjs getInitialProps focuses on fetching static data that enhances performance and SEO. The choice between them depends on the specific requirements of your application and the type of data you need to access.

When Should I use getServerSideProps?

getServerSideProps ScenarioUseAvoid
Content with dynamic data or personalized dataYesNo
Content that requires real-time data or live updatesYesNo
Content that varies per user or requestYesNo
Content that needs to be updated frequentlyYesNo
Content with static data that should be pre-rendered for performanceNoYes
Content that needs to achieve excellent SEO without data fetching on the client-sideNoYes

Let’s take a look at an example of how to fetch user data using the getServerSideProps function in a Next.js application.

Create a new user.tsx file and update it with the following TypeScript code.

import type { InferGetServerSidePropsType, GetServerSideProps } from "next";
import { Nav } from "./components/Nav";

type User = {
  name: string;
  email: string;
  address: { stress: string };
  phone: string;
};

export const getServerSideProps = (async () => {
  // Fetch data from external API
  const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
  const user = await res.json();
  // Pass data to the page via props
  return { props: { user } };
}) satisfies GetServerSideProps<{ user: User }>;

export default function Page({
  user,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <main className='bg-white min-h-screen text-slate-700 p-10'>
      <Nav />
      <h2 className='font-bold text-xl'>{user.name}</h2>
      <p>{user.username}</p>
      <p>{user.email}</p>
      <p>{user.address.street}</p>
      <p>{user.phone}</p>
    </main>
  );
}

This code snippet fetches user data from an external API on the server-side using getServerSideProps and passes it to the page component as props.

The above code will produce the following output:

The API call is not visible in the browser network because it happens on the server-side before the page is rendered and it’ll not log the data in the client even when we perform a client navigation.

The console.log(user) will only appear on the terminal as well, and not on the browser console.

What is the difference between getInitialProps and getStaticProps props

FeaturegetInitialPropsgetStaticProps
Execution timingAt runtime (on first request and server-side)At build time (server-side only)
Data fetchingCan be dynamic or staticAlways static, predefined data
Page renderingServer-side with fetched dataPre-rendered with injected data
Initial load timeSlightly slower, data fetched on the first requestFastest, no data fetching on client-side
SEOGood, data available for search enginesExcellent, complete page with data for search engines
Dynamic data suitabilityLimited, best for initial data or shared across usersNot ideal, data is static and cannot change
PerformanceCan add server load for subsequent requestsEfficient, minimal server load after build
RevalidationNot applicable, data fetched once on the first requestOptional, requires manual or automatic configuration
Use casesInitial data retrieval, shared user information, common configurationStatic content like blog posts, landing pages, unchanging data
Props returnedAn object containing any valueObject containing props, optional revalidate, and notFound
Function Signatureasync (context: NextPageContext) => {}async () => {} or async (context: GetStaticPropsContext) => {}
Server-Side RenderingYesNo
Static Site GenerationNoYes

When Should I use getStaticProps?

getStaticProps ScenarioUseAvoid
Content with unchanging dataYesNo
Content requiring fast initial load times or excellent SEOYesNo
Dynamic content or personalized dataNoYes
Frequently updated dataNoYes

In cases where your content is static and doesn’t change frequently, or when you need fast initial load times and excellent search engine optimization, getStaticProps is the ideal choice.

However, for dynamic or personalized data, as well as content that is updated frequently, it’s better to avoid using getStaticProps.

Now, let’s take a look at an example of how to fetch post data using the getStaticProps function in a Next.js application.

Update your index.tsx file with the following TypeScript code.

import type { InferGetStaticPropsType, GetStaticProps } from "next";
import { Nav } from "./components/Nav";

type Posts = {
  id: string;
  userId: string;
  title: string;
  body: string;
}[];

export const getStaticProps = (async (context) => {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts/");
  const posts = await res.json();
  console.log(posts);
  return { props: { posts } };
}) satisfies GetStaticProps<{
  posts: Posts;
}>;

export default function Page({
  posts,
}: InferGetStaticPropsType<typeof getStaticProps>) {
  return (
    <main className='flex flex-col gap-5 bg-white min-h-screen text-slate-700 p-10'>
      <Nav />
      {posts.map(({ id, title, body, userId }) => {
        return (
          <article key={id}>
            <h2 className='font-bold text-xl'>{title}</h2>
            <p>{body}</p>
            <span>Author: {userId}</span>
          </article>
        );
      })}
    </main>
  );
}

Below is the output of the request; the API call is also not visible in the network tab and it’ll not log the data in the client even when we perform client navigation.

The console.log(posts) will only appear on the terminal as well, and not on the browser console.

This shows that the getStaticProps function only gets called on the server-side.

Below is the final output and demonstration of the getInitialProps, getServerSideProps and getStaticProps data fetching methods.

If your code does not function as illustrated above, carefully retrace your steps and verify that you have named your files accurately, as specified in each of the sections.

Double-check the implementation of the getInitialProps, getServerSideProps, and getStaticProps data fetching methods, and ensure that you have followed the API structure and instructions provided.

You can also watch this YouTube video tutorial for more explanation and further study on Next.js Server Side Rendering and getInitialProps.

Wrapping Up getInitialProps in Next.js

The getInitialProps method in Next.js offers a powerful way to pre-render data on the server-side, enhancing application load time and user experience.

Despite being a legacy API with its own limitations, it has unique use cases especially when dealing with data that is consistent across users or pages.

However, the introduction of getServerSideProps and getStaticProps provides more flexibility and efficiency in handling dynamic and static data respectively.

The choice between these methods depends on your application’s specific needs. As you continue to build with Next.js, understanding these concepts and their differences will be crucial in optimizing your web application’s performance and SEO.

Check out Purecode AI!

I recommend you try out Purecode AI, an AI tool that can generate custom HTML, CSS, and JavaScript components. Here are some of its features:

  • It uses an AI assistant to generate thousands of responsive pre-made components for you.
  • The components come with default styling using CSS, Tailwind CSS, or your own custom styles so you can match your brand’s design.
  • You can easily customize the generated components to suit your specific needs – change colors, spacing, paddings, margins, etc.
  • It generates both the HTML markup and CSS styles for the components, saving you development time.
  • It also includes some JavaScript functionality within the components to make them interactive.
Ayodele Samuel Adebayo

Ayodele Samuel Adebayo