09 Feb 2024




Intermediate

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). getStaticProps is specifically designed for SSG, where pages are generated at build time and served as static HTML files.

  • Asynchronous Data Fetching: getStaticProps is 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 getStaticProps must be an object with a props key containing the data that will be passed to the page component for rendering. Optionally, it can also contain a revalidate key which defines the time in seconds after which a page re-generation will occur.

  • Revalidation: By setting the revalidate key 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:

  1. Import Statements: We import GetStaticProps from Next.js. This type specifies the shape of the props that getStaticProps will return.

  2. Interfaces: We define an interface Post to represent the structure of a post object, and HomeProps to specify the props that the Home component expects.

  3. Home Component: This is a simple functional component that renders a list of posts.

  4. 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 a revalidate key, specifying that Next.js should re-generate the page after 60 seconds.

  5. Export: We export both the Home component and the getStaticProps function 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.

next.js
getstaticprops