NextJS provides a special function getStaticProps()
that allows us to define a component for prerendering. While the default functionality works well enough, there are also several configuration options. In this post, we will look at NextJS getStaticProps configuration options.
Also, we will look at the special context object that is provided as input to the getStaticProps()
function and how we can use it in our application.
In case you are not aware of it, check out this post on NextJS prerendering.
1 – NextJS getStaticProps()
Configuration Options
Below are the various configuration options we can use to customize the behaviour of getStaticProps()
function.
- props – This is the most important configuration option and basically the reason for using this function. Whatever props we provide as part of this configuration property is made available to the actual component. Moreover, the props are provided during the pre-rendering phase.
- revalidate – The
revalidate
property accepts time in seconds. We can userevalidate
to re-generate our page at fixed intervals of time if a request is made to the page again. Basically,revalidate
allows us to have best of both worlds i.e. initial rendering and pre-rendering of data. - redirect – This property is used to redirect to another page in case of some condition. For example, suppose we are not able to render the original component for some data reason, we can set the
redirect
property to return to some other route of our application. - notFound – As the name suggests, the
notFound
attribute signals to NextJS that the page is not found and hence, the 404 page should be shown to the client. This is also handy in case of some data issues.
See below example on using the above configuration options for getStaticProps()
.
export async function getStaticProps() {
console.log('Regenerating...')
const filePath = path.join(process.cwd(), 'data', 'dummy-backend.json');
const jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData);
return {
props: {
products: data.products
},
revalidate: 2
};
}
Here, we are using the props
and revalidate
options in the object returned from getStaticProps()
.
Similarly, we can also use redirect
property to redirect to a different route in case of a particular condition.
if (!product) {
return {
redirect: '/not-found'
}
}
Alternatively, we can also set the notFound property to trigger the default NextJS 404 response.
if (!product) {
return {
notFound: true
}
}
2 – NextJS getStaticProps()
Context Object
The getStaticProps()
function can also accept a context object. This object is provided by NextJS itself.
A real world usage of the context object would be in the case of dynamic pages. For example, if we have a specific page for every product and we have routes based on product id such as /products/<pid>
, we can create a dynamic route in NextJS to handle these pages.
See below example of a NextJS dynamic route page.
import fs from 'fs/promises';
import path from 'path';
import { Fragment } from "react";
function ProductDetailPage(props) {
const { fetchedProduct } = props;
return (
<Fragment>
<h1>{fetchedProduct.title}</h1>
<p>{fetchedProduct.description}</p>
</Fragment>
)
}
async function getData() {
const filePath = path.join(process.cwd(), 'data', 'dummy-backend.json');
const jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData);
return data;
}
export async function getStaticProps(context) {
const { params } = context;
const productId = params.pid;
const data = await getData();
const product = data.products.find(product => product.id === productId);
if (!product) {
return {
notFound: true
}
}
return {
props: {
fetchedProduct: product
}
}
}
In the above example, we accept the context object as input to the getStaticProps()
function. From the context object, we extract params. And within the params, we can get access to product id in the route path.
Next, using this product id, we fetch the product record from the dummy-backend.json
file and return the data as props to the main ProductDetailPage
component.
Below is the dummy data file for reference.
{
"products": [
{ "id": "p1", "title": "Product 1", "description": "This is Product 1"},
{ "id": "p2", "title": "Product 2", "description": "This is Product 2"},
{ "id": "p3", "title": "Product 3", "description": "This is Product 3"}
]
}
Conclusion
With this, we have successfully understood the NextJS getStaticProps function, its configuration parameters. Also, we gave a quick look to the context object that has useful properties to help in our application logic.
In the next post, we look at pre-rendering dynamic routes using NextJS.
Want to build bigger NextJS apps? Check out this post on creating a NextJS event management application from scratch.
If you have any comments or queries about this post, please feel free to mention them in the comments section below.
0 Comments