In the first installment of this series we brushed on the differences between Static Site Generation and Server Site Rendering in Next.js. Both have their use cases, but it is recommended by the creators of Next to use Static Site Generation, since it is more optimal to initially build a page’s HTML and reuse the layout with subsequent requests, as opposed to rendering HTML with every request made. I also mentioned how a page component doesn’t contain any render logic. However, if necessary, we can implement some logic that fetches any external data that a component may require to pre-render, like a list of a user’s blog posts from a CMS, or a newsfeed.
Fetching External Data
Next.js contains a few built-in methods used for fetching data by calling to external API routes. One of these methods, getStaticProps()
, fetches the data at the received context at build time. Of course, this means that we must use our better judgment to determine if it is feasible to do so, based on the type of data needed. getStaticProps()
is ideal for data that is publicly accessible; 'data that would not require an authorization token to access.
export async function getStaticProps(context) {
//dynamic route to call
const res = await fetch(‘http://example.com/api/posts’);
const data = await res.json();
//error handling + return props object with serializable data
if (!data) {
{ notFound: true }
}
return {
props: {}
}
}
The getStaticProps
function asynchronously receives our context. After fetching our data from an API, it returns our data as a serializable props
object.
Static Site generation is optimal for pages such as landing sites that don’t require any handling of data that gets updated regularly. By rendering our HTML at build time we also improve our SEO.
Another option for data fetching is the getServerSideProps
function. This function runs at build time as well, with the major difference being that getServerSideProps
renders pages with every request. Like getStaticProps
, this function fetches data from the API and returns the data as props in an object.
async getServerSideProps(context) {
const res = await fetch(‘http://example.com/api/posts’);
const data = await res.json();
//error handling + return props object with serializable data
if (!data) {
{ notFound: true }
}
return {
props: {}
}
}
To reiterate, it's more optimal to pre-render a web-application's pages at build time, than to render them every time a request is made. After the initial build, all markup and all logic is now rendered on the client side, and is now reusable, making re-rendering not necessary.
Top comments (0)