In Next.js, getStaticProps
is a powerful function that allows you to pre-render pages at build time. It enables you to fetch data and generate static HTML for your pages before deployment, offering an excellent performance boost, especially for pages that don’t require real-time data updates on every request.
By using getStaticProps
, Next.js can generate static files for your pages, which can be served by a CDN (Content Delivery Network), reducing server load and delivering content quickly to users. This is a key feature for Static Site Generation (SSG) and is especially useful for SEO and performance optimization.
In this guide, we’ll explore how to leverage getStaticProps
to optimize the performance of your Next.js application.
1. What is getStaticProps
?
getStaticProps
is an asynchronous function in Next.js that you can export from a page component. It runs at build time and allows you to fetch data, which is then passed to the page component as props. The page is pre-rendered with this data into static HTML and saved as part of the build process.
This is different from Server-Side Rendering (SSR) (getServerSideProps
), which fetches data at request time, or Client-Side Rendering (CSR), where the data is fetched after the page loads.
2. How getStaticProps
Works
Here’s how getStaticProps
works step-by-step:
- Page Request: When you request a page that uses
getStaticProps
, Next.js fetches the data defined in the function during the build process (before deployment). - Data Fetching: You can fetch data from an API, database, or file system inside
getStaticProps
. The data will be available during build time, not at request time. - Page Pre-rendering: Once the data is fetched, Next.js generates a static HTML page that includes the fetched data. This HTML page is served to the user.
- Serving the Static Page: The generated static page is stored and served from a CDN or the server, offering fast loading times.
3. Example: Using getStaticProps
Let’s look at an example of how to use getStaticProps
to preload data for a blog page:
import React from 'react';
const BlogPage = ({ posts }) => {
return (
<div>
<h1>Blog Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
};
// Fetching blog posts at build time
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
return {
props: { posts }, // The posts will be passed to the page as props
};
}
export default BlogPage;
How the Example Works:
getStaticProps
fetches data from a mock API (jsonplaceholder.typicode.com
).- The data (
posts
) is passed as props to theBlogPage
component. - During build time, Next.js generates a static HTML file with the fetched blog posts. This page is then ready to be served to users immediately.
4. When to Use getStaticProps
You should use getStaticProps
when:
- Static Content: The page doesn’t require real-time data (e.g., a blog, a product listing, a marketing page).
- Performance Optimization: You want fast load times and improved performance by pre-rendering the content during the build process.
- SEO: You want search engines to crawl the fully rendered HTML, ensuring better SEO.
- No Need for Frequent Updates: The data on the page doesn’t change frequently or can be re-generated periodically (e.g., daily, weekly).
5. Benefits of getStaticProps
for Performance Optimization
- Fast Load Times: Since the pages are pre-rendered at build time, they can be served from a CDN, resulting in extremely fast page loads.
- Reduced Server Load: Static pages do not require a request to the server on every page load. This reduces the load on the server and improves scalability.
- Improved SEO: Search engines can crawl and index the fully rendered HTML, making it easier for your content to rank in search results.
- Cacheability: Static pages can be cached at the CDN level, improving the user experience by reducing server response times.
6. Incremental Static Regeneration (ISR)
Next.js offers a feature called Incremental Static Regeneration (ISR), which allows you to update static pages after build time without rebuilding the entire site.
You can specify how often you want to regenerate a page by adding the revalidate
property to getStaticProps
:
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
return {
props: { posts },
revalidate: 60, // Regenerate the page every 60 seconds
};
}
How ISR Works:
- The page is statically generated at build time.
- After the page is built and deployed, Next.js will regenerate the page in the background when a request comes in, if the specified
revalidate
time has passed. - The regenerated page will be served for subsequent requests, ensuring the data stays up-to-date without needing a full rebuild.
7. Handling Dynamic Routes with getStaticProps
For dynamic routes (e.g., a product or blog post page), Next.js allows you to use getStaticPaths
in combination with getStaticProps
to generate static pages for dynamic routes.
import React from 'react';
const Post = ({ post }) => {
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
};
// Fetching data for dynamic routes
export async function getStaticPaths() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
// Generate paths for each post
const paths = posts.map((post) => ({
params: { id: post.id.toString() },
}));
return {
paths,
fallback: false, // Show 404 page if path doesn't exist
};
}
// Fetching data for a specific post
export async function getStaticProps({ params }) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`);
const post = await res.json();
return {
props: { post },
};
}
export default Post;
In this example:
getStaticPaths
fetches the list of post IDs and generates static paths for each post.getStaticProps
fetches the data for each post using the dynamicid
parameter from the path.
8. Performance Considerations with getStaticProps
Although getStaticProps
is a great way to optimize performance, there are a few things to keep in mind:
- Data Fetching Time: If your data fetching takes a long time, it can increase your build time. Ensure that you optimize API calls and avoid unnecessary delays in fetching data.
- Build Time: For larger sites, pre-rendering pages at build time might take a long time. Consider using ISR to update pages in the background instead of rebuilding the entire site on every change.
- Stale Data: If you need to show frequently changing data,
getStaticProps
might not be suitable unless combined with ISR or revalidation strategies.