Next.js Data Fetching Methods
Last Updated :
23 Jul, 2025
Next.js is a React-based full-stack framework that enables functionalities like pre-rendering of web pages. Unlike traditional react app where the entire app is loaded on the client, Next.js allow the web page to be rendered on the server, which is great for performance and SEO. You can learn more about Next.js here.
Next.js provides three data fetching methods and based on these methods, it renders content differently. (You can learn about different rendering methods here.
- getStaticProps
- getStaticPaths
- getServerSideProps
getStaticProps: It preloads all of the data needed for a given page and renders pages ahead of the user's request at build time. For speedier retrieval, all of the data is cached on a headless CMS. For better SEO performance, the page is pre-rendered and cached. If no other data fetching method is specified, Next.js will use this by default. It is used to implement Static Site Generation and Incremental Site Regeneration.
Properties of getStaticProps:
- It can only be exported from the page file, not the component file.
- It only runs on build time.
- It runs on every subsequent request in development mode.
- Its code is completely excluded from the client-side bundle.
getStaticPaths: If a page uses getStaticProps and has dynamic routes, it must declare a list of paths that will be statically generated. Next.js will statically pre-render all the paths defined by getStaticPaths when we export a function named getStaticPaths from a page.
Properties of getStaticPaths:
- It can only be exported from a page file.
- It is meant for dynamic routes.
- Page must also implement getStaticProps.
- It runs only at build time in production.
- It runs on every request in development mode.
getServerSideProps: It will pre-render the page on every subsequent request. It is slower as compared to getStaticProps as the page is being rendered on every request. getServerSideProps props return JSON which will be used to render the page all this work will be handled automatically by Next.js. It could be used for calling a CMS, database, or other APIs directly from getServerSideProps. It is used to implement Server Side Rendering.
Properties of getServerSideProps:
- It runs on every subsequent request in development as well as production mode.
- Its code is excluded from the client-side bundle.
- It can only be exported from page file.
When to use which data fetching method: If your page’s content is static or doesn’t change frequently then you should go for getStaticProps as it builds pages on build time hence increasing performance. If your page has dynamic routes then getStaticPaths should be used along with getStaticProps.
But if your website contains a page whose data changes very frequently then you must use getServerSideProps as it fetches fresh data on every request.
Example: We will build a simple Next Js application with three pages of albums, posts, and a users page with dynamic routes. All three pages will implement different data fetching methods. For this example, we will use JSONPlaceholder API to fetch random data.
Run the following command to create a new Next Js application (Make sure you have NPM and node installed) :
npx create-next-app@latest myproject
When we open our project in a code editor, we see a straightforward project structure. For the scope of this tutorial, we will only focus on /pages directory. We'll first cleanup the /pages/index.js file. Then we'll create two new pages albums, posts, and a dynamic routes page /users/[id].
Project Structure:
/pages/index.js - We'll first cleanup the homepage (index), delete all boilerplate code and add links to all the pages we'll be implementing for easier Navigation.
JavaScript
import React from 'react'
import Link from 'next/link'
const Home = () => {
// This is the home page which will
// contain links to all other pages
return (
<>
<h1>Hello Geeks</h1>
<ul>
<li>
getStaticProps :
<Link href={'/about'}>About Page</Link>
</li>
<li>
getStaticPaths :
<Link href={'/users/1'}>User 1</Link>
</li>
<li>
getServerSideProps :
<Link href={'/posts'}>Posts Page</Link>
</li>
</ul>
</>
)
}
export default Home
/pages/albums.jsx - Albums page will implement static site generation using getStaticProps, we will export the data fetching method along with the page component. We can send fetched data to the page component using props. Next Js will fetch all the albums at build time before the user's request.
JavaScript
import React from 'react'
export const getStaticProps = async () => {
// Fetching data from jsonplaceholder.
const res = await fetch(
'https://jsonplaceholder.typicode.com/albums');
let allAlbums = await res.json();
// Sending fetched data to the page component via props.
return {
props: {
allAlbums: allAlbums.map((album) => album.title)
}
}
}
const Albums = ({ allAlbums }) => {
return (
<div>
<h1>All Albums</h1>
{allAlbums.map((album, idx) => (
<div key={idx}>{album}</div>))
}
</div>
)
}
export default Albums
/pages/posts.jsx - Posts page will implement server-side rendering using getServerSideProps. It'll fetch posts data and build page at each request made by user., and send fetched data to the component using props.
JavaScript
import React from 'react'
export const getServerSideProps = async (ctx) => {
// ctx is the context object which contains the request,
// response and props passed to the page.
// fetching data from jsonplaceholder.
const res = await fetch(
'https://jsonplaceholder.typicode.com/posts');
let allPosts = await res.json();
// Sending fetched data to the page component via props.
return {
props: {
allPosts: allPosts.map((post) => post.title)
}
}
}
const Posts = ({ allPosts }) => {
return (
<div>
<h1>All Posts</h1>
{allPosts.map((post, idx) => (
<div key={idx}>{post}</div>))}
</div>
)
}
export default Posts
/pages/users/[id].jsx - Because this is a dynamic page, we must pre-define all of the user Ids so that Next Js can retrieve their data at build time. As a result, we use getStaticPaths and define ten user Ids.
JavaScript
import React from "react";
export const getStaticProps = async (ctx) => {
// ctx will contain request parameters
const { params } = ctx;
// We will destructure id from the parameters
const userId = params.id;
// Fetching user data
const res = await fetch(
`https://jsonplaceholder.typicode.com/users/$%7BuserId%7D%60
);
const userData = await res.json();
// Sending data to the page via props
return {
props: {
user: userData,
},
};
};
export const getStaticPaths = () => {
// Specifying all the routes to be
// pre-rendered by next js
return {
paths: [
{ params: { id: "1" } },
{ params: { id: "2" } },
{ params: { id: "3" } },
{ params: { id: "4" } },
{ params: { id: "5" } },
{ params: { id: "6" } },
{ params: { id: "7" } },
{ params: { id: "8" } },
{ params: { id: "9" } },
{ params: { id: "10" } },
],
fallback: false,
};
};
const User = ({ user }) => {
return (
<>
<h1>User {user.id}</h1>
<h2>Name : {user.name}</h2>
<h2>Email : {user.email}</h2>
</>
);
};
export default User;
Run the application: Open the terminal and enter the following command.
npm run dev
Output:
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
4 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects