Data fetching in Next.js Using SSG and SSR
In Next.js, fetching data faster is all about choosing the right data-fetching strategy based on when and how often your data changes. Next.js provides multiple built-in methods like getStaticProps
, getServerSideProps
, getStaticPaths
, and Client-Side Fetching with SWR.
Steps to Create the NextJS App
Step 1: Create the app using the following command:
npx create-react-app fetchdata
Step 2: Navigate to the root directory of your project using the following command:
cd fetchdata
Project Structure:
Example: Create a file name it as "server.js" for API setup for data fetching:
//server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const posts = [
{
"userId": 1,
"id": 1,
"title": `sunt aut facere repellat provident occaecati
excepturi optio reprehenderit`,
"body": `quia et suscipit\nsuscipit recusandae consequuntur expedita
et cum\nreprehenderit molestiae ut ut quas totam\nnostrum
rerum est autem sunt rem eveniet architecto`
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": `est rerum tempore vitae\nsequi sint nihil reprehenderit dolor
beatae ea dolores neque\nfugiat blanditiis voluptate porro vel
nihil molestiae ut reiciendis\nqui aperiam non debitis possimus
qui neque nisi nulla`
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": `et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut
ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae
porro eius odio et labore et velit aut`
},
{
"userId": 1,
"id": 4,
"title": "eum et est occaecati",
"body": `ullam et saepe reiciendis voluptatem adipisci\nsit amet
autem assumenda provident rerum culpa\nquis hic commodi
nesciunt rem tenetur doloremque ipsam iure\nquis sunt
voluptatem rerum illo velit`
},
{
"userId": 1,
"id": 5,
"title": "nesciunt quas odio",
"body": `repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem
\sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest
aut tenetur dolor neque`
},
{
"userId": 1,
"id": 6,
"title": "dolorem eum magni eos aperiam quia",
"body": `ut aspernatur corporis harum nihil quis provident sequi\nmollitia
nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit
accusantium quas\nvoluptate dolores velit et doloremque molestiae`
},
{
"userId": 1,
"id": 7,
"title": "magnam facilis autem",
"body": `dolore placeat quibusdam ea quo vitae\nmagni quis enim qui quis
quo nemo aut saepe\nquidem repellat excepturi ut quia\nsunt ut
sequieos ea sed quas`
}
];
// Route to get all posts
app.get('/posts', (req, res) => {
res.json(posts);
});
// Route to get a specific post by its ID
app.get('/posts/:id', (req, res) => {
const postId = parseInt(req.params.id);
const post = posts.find(post => post.id === postId);
if (post) {
res.json(post);
} else {
res.status(404).json({ error: 'Post not found' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
- This code creates an Express server that serves blog posts from a static array.
- It has two routes:
/posts
returns all posts, and/posts/:id
returns a single post by its ID. - Finally, the server listens on the given port and logs the URL where itâs running.
Static Generation using getStaticProps(SSG) :
Static Generation is a Next.js feature that generates HTML pages at build time. This means that the content of these pages is pre-rendered and served as static files, making them extremely fast to load. Static Generation is suitable for pages with content that doesn't change frequently, such as marketing pages, blogs, or product listings.
Example : Publishing Articles Using SSG â Like GeeksforGeeks
- Each article appears as a separate page, but you donât need to manually create HTML, CSS, or JS for it.
- SSG (Static Site Generation) automatically generates the HTML for every article at build time.
- Once generated, the same pre-built page is served to all users.
- Pages load quickly and are SEO-friendly.
- The developer only provides the article data (JSON, Markdown, etc.), and the page is built automatically.
- Using dynamic routes, multiple article pages are created without writing extra code.
- No manual coding is required for each article, making site maintenance easier.
- SSG prepares all pages at build time, so the server doesnât need to generate them on every request.

How it Works:
- When you use getStaticProps in a Next.js page, Next.js will pre-render that page at build time.
- During the build process, Next.js calls getStaticProps, fetches data, and generates the HTML for the page with that data.
- The generated HTML is then served to the client, making subsequent visits to the page very fast as the content is already there.
Syntax:
export async function getStaticProps() {
// Fetch data from an API or database
const data = await fetchData();
return {
props: {
data,
},
};
}
Example: Below is an example of Fetching data using getStaticProps in NextJS App.
// index.js
export default function Home({ data }) {
return <div>{JSON.stringify(data)}</div>;
}
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
return {
props: {
data,
},
};
}
Output

Server-side Rendering using getServerSideProps (SSR) :
Server-side Rendering (SSR) in Next.js involves fetching data on each request from the server before rendering the page. This ensures that the content is always up-to-date and can be personalized for each user. SSR is suitable for pages with dynamic content or data that changes frequently.

How it Works:
- When a user visits an SSR-enabled page, Next.js calls getServerSideProps.
- Inside getServerSideProps, you can fetch data from an API, database, or any other source.
- Next.js then generates the HTML for the page with the fetched data and sends it to the client.
Syntax:
export async function getServerSideProps() {
// Fetch data from an API or database
const data = await fetchData();
return {
props: {
data,
},
};
}
Example: Below is an example of fetching data using getServerSideProps in NextJS App.
// product/[id].js
export default function Product({ data }) {
return <div>{JSON.stringify(data)}</div>;
}
export async function getServerSideProps(context) {
const { params } = context;
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/%5Bid%5D%60);
const data = await res.json();
return {
props: {
data,
},
};
}