What is getStaticProps and when do you use it?

getStaticProps is a Pages Router function that runs at build time (and during ISR revalidation) on the server to fetch data for a page. Next.js renders the page to static HTML plus JSON, served from a CDN. Use it when the data is the same for every visitor.

Key facts

  • Export it from a page file in pages/. It never runs in the browser and is removed from the client bundle, so you can query databases directly.
  • It receives a context with params (for dynamic routes), locale, draftMode and preview information.
  • It returns one of:
    • { props } for the page component,
    • { props, revalidate: 60 } to enable ISR,
    • { notFound: true } for a 404,
    • { redirect: { destination, permanent } }.
  • Dynamic routes also need getStaticPaths.
  • In next dev it runs on every request.

When to use it

Marketing pages, blog posts, docs and product catalogs: public content that changes rarely or can be revalidated.

When not to

Per-user data (use getServerSideProps or client fetching) or data that must be fresh on every request.

App Router equivalent

There is no getStaticProps in app/. Fetch in an async Server Component. With Cache Components, wrap the data function in "use cache" with cacheLife('days') or similar; content with no request data is prerendered automatically. revalidate maps to cacheLife, and notFound maps to notFound().

Code example

tsx
1// pages/blog/index.tsx
2import type { GetStaticProps, InferGetStaticPropsType } from "next";
3
4type Post = { id: number; title: string };
5
6export const getStaticProps = (async () => {
7 const res = await fetch("https://cms.example.com/posts");
8 if (!res.ok) return { notFound: true };
9
10 const posts: Post[] = await res.json();
11 return {
12 props: { posts },
13 revalidate: 3600, // ISR: regenerate at most once per hour
14 };
15}) satisfies GetStaticProps<{ posts: Post[] }>;
16
17export default function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps>) {
18 return (
19 <ul>
20 {posts.map((p) => (
21 <li key={p.id}>{p.title}</li>
22 ))}
23 </ul>
24 );
25}
26
27// App Router equivalent (Cache Components):
28// async function getPosts() { "use cache"; cacheLife("hours"); return db.post.findMany(); }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app