Skip to main content

Using getStaticProps for Static Generation

Introduction

In this tutorial, we are going to explore one of the most important concepts in Next.js: getStaticProps for static generation. getStaticProps is a built-in async function provided by Next.js that enables you to fetch data at build time and render it as static HTML.

What is Static Generation?

Static Generation is the rendering method where the HTML pages are generated at build time. This means that the pages are generated once and reused for each request, making the app extremely fast and efficient. This is possible because Next.js pre-renders every page in advance, before a request is made.

Understanding getStaticProps

The getStaticProps function is used to generate static pages with dynamic data. It runs at build time in production and generates the HTML for a page, along with a JSON file that contains the data for the page.

Here's a simple syntax representation of getStaticProps:

export async function getStaticProps(context) {
// Fetch data here...
return {
props: { /* the returned data */ },
}
}

The getStaticProps function should return an object with the props key, and the value should be an object containing all the data you want to pass to the component.

Using getStaticProps: An Example

Let's illustrate the use of getStaticProps with a simple example.

Assume we have a blog and we want to display a list of blog posts. We are going to fetch the posts from an external API at build time.

First, let's import the necessary modules and define our component:

import axios from 'axios';

const Blog = ({ posts }) => {
return (
<div>
<h1>My Blog Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};

export default Blog;

In the above block, we've created a simple functional component Blog that accepts posts as props and renders them in a list.

Now, let's add the getStaticProps function to fetch the blog posts:

export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
const posts = res.data;

return {
props: {
posts,
},
};
}

In this function, we're fetching data from a placeholder API. The fetched posts are then returned as a prop to the Blog component.

Conclusion

That's it! You've successfully used getStaticProps for static generation in Next.js. Remember, getStaticProps only runs on server side, so it will never run on the client side. This means you can write code such as direct database queries without them being sent to browsers.

Understanding how to utilize getStaticProps effectively is an essential skill when working with Next.js. It allows us to leverage the power of static generation, providing users with fast, efficient, and SEO-friendly web pages. Happy coding!