getStaticProps() is a data-fetching method used in the Pages Router (pages/ directory) of Next.js to generate pages at build time.
Note:
getStaticProps()is not used in the App Router (app/). In modern Next.js (App Router), you usefetch()with caching options likerevalidate.
What is getStaticProps()?
It fetches data during:
next build
↓
Fetch Data
↓
Generate HTML
↓
Store Static HTML
↓
Serve to all users
Example
pages/jobs.js
export async function getStaticProps() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
const jobs = await response.json();
return {
props: {
jobs
}
};
}
export default function Jobs({ jobs }) {
return (
<>
<h1>Jobs</h1>
{jobs.map((job) => (
<div key={job.id}>
{job.title}
</div>
))}
</>
);
}
How it Works
When you run:
npm run build
Next.js executes:
getStaticProps()
only once.
Generated HTML might look like:
<h1>Jobs</h1>
<div>Software Developer</div>
<div>React Developer</div>
<div>Node.js Developer</div>
This HTML is stored and served directly.
Benefits
✅ Very fast
✅ SEO friendly
✅ Reduced server load
✅ Good for public pages
With ISR (Revalidation)
You can refresh the static page automatically.
export async function getStaticProps() {
const response = await fetch(
"https://api.example.com/jobs"
);
const jobs = await response.json();
return {
props: {
jobs
},
revalidate: 60
};
}
Meaning:
Generate page
Cache it
After 60 seconds
Regenerate automatically
Equivalent App Router code:
const response = await fetch(
"https://api.example.com/jobs",
{
next: {
revalidate: 60
}
}
);
Dynamic Routes Example
pages/job/[slug].js
export async function getStaticPaths() {
return {
paths: [
{ params: { slug: "react-developer" } },
{ params: { slug: "nodejs-developer" } }
],
fallback: false
};
}
export async function getStaticProps({ params }) {
const response = await fetch(
`https://api.example.com/job/${params.slug}`
);
const job = await response.json();
return {
props: {
job
}
};
}
export default function JobDetail({ job }) {
return <h1>{job.title}</h1>;
}
During build:
/job/react-developer
/job/nodejs-developer
are generated as static HTML pages.
Pages Router vs App Router
| Pages Router | App Router |
|---|---|
getStaticProps() | fetch() |
getServerSideProps() | cache: "no-store" |
getStaticPaths() | generateStaticParams() |
revalidate | next: { revalidate } |
Pages Router
export async function getStaticProps() {
return {
props: {}
};
}
App Router
const response = await fetch(
"https://api.example.com/jobs",
{
next: {
revalidate: 60
}
}
);
Interview Answer
getStaticProps() is a Next.js Pages Router function that fetches data at build time and generates static HTML. It improves performance and SEO because the page is pre-rendered and served directly to users. It can also support Incremental Static Regeneration using the revalidate option.
