09 Feb 2024
getStaticProps is a special function in Next.js which runs only on the server-side, used for data fetching during static site generation (SSG). It allows you to pre-render a page with data fetched at build time, resulting in faster page loads and improved SEO performance.
⭐Note: As getStaticProps runs only on the server-side, it will never run on the client-side. It won’t even be included in the JS bundle for the browser, so you can write direct database queries without them being sent to browsers.
Key points about getStaticProps:
-
Static Site Generation (SSG): Next.js supports several rendering methods, including server-side rendering (SSR) and static site generation (SSG).
getStaticPropsis specifically designed for SSG, where pages are generated at build time and served as static HTML files. -
Asynchronous Data Fetching:
getStaticPropsis an asynchronous function that enables you to fetch data from any data source, such as APIs, databases, or the file system. This data is then used to pre-render the page. -
Context: Inside
getStaticProps, you have access to a context object containing parameters such as the route's pathname and query parameters. This context allows you to dynamically fetch data based on the route or query parameters. -
Return Value: The return value of
getStaticPropsmust be an object with apropskey containing the data that will be passed to the page component for rendering. Optionally, it can also contain arevalidatekey which defines the time in seconds after which a page re-generation will occur. -
Revalidation: By setting the
revalidatekey in the return object, you can specify how often Next.js should re-generate the page. This allows you to ensure that your static pages remain up-to-date with the latest data.
TypeScript example of using getStaticProps in Next.js:
// pages/index.tsx
import { GetStaticProps } from 'next';
interface Post {
id: number;
title: string;
}
interface HomeProps {
posts: Post[];
}
const Home: React.FC<HomeProps> = ({ posts }) => {
return (
<div>
<h1>Latest Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export const getStaticProps: GetStaticProps<HomeProps> = async () => {
// Fetch data from an API, database, or file system
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts: Post[] = await response.json();
// Return data as props
return {
props: {
posts,
},
revalidate: 60, // re-generate the page after 60 seconds
};
};
export default Home;
Explanation:
-
Import Statements: We import
GetStaticPropsfrom Next.js. This type specifies the shape of the props thatgetStaticPropswill return. -
Interfaces: We define an interface
Postto represent the structure of a post object, andHomePropsto specify the props that the Home component expects. -
Home Component: This is a simple functional component that renders a list of posts.
-
getStaticProps Function: This is an asynchronous function that fetches data from an API (in this case, JSONPlaceholder) using
fetch. It retrieves an array of posts, and returns them as props along with arevalidatekey, specifying that Next.js should re-generate the page after 60 seconds. -
Export: We export both the
Homecomponent and thegetStaticPropsfunction from the module.
In summary, getStaticProps is used to fetch data at build time and pass it as props to the page component in Next.js. This enables static site generation with dynamic data, resulting in improved performance and SEO.