DEV Community

Cover image for Unlock the Power of Static Sites with Next.js: A Guide to Static Site Generation
Kristijan Pajtasev
Kristijan Pajtasev

Posted on • Originally published at kristijan-pajtasev.Medium

Unlock the Power of Static Sites with Next.js: A Guide to Static Site Generation

Introduction

Static site generation is a powerful tool to improve the application's speed, security, and overall performance. Next.js is a popular static site generation framework that offers developers an easy way to leverage the power of static sites. It provides a robust set of features such as automatic code splitting, routing, and server-side rendering to make development easier and faster. With Next.js, developers can quickly create static websites that are secure, performant, and SEO friendly. In this article, we'll discuss the benefits of using Next.js for static site generation and how it can help developers create powerful and efficient websites.

NextJS logo

Benefits of Using Next.js for Static Site Generation

  • Performance and Speed

    Static-site generation shows performance improvement when compared to server-side generation and client-side generation. This way, content is generated during the build of the application. That means on the request, content is ready and can be immediately sent to the user. This is a huge improvement because in both other cases, it needs to be first generated to be visible or sent. If we are talking about the client side, then libraries are loaded, data is fetched, and content is generated for it and displayed in the browser. Server-side, on requests, gets data, triggers a build, and sends the final bundle as a response to the user which gets displayed.

  • Security and Reliability

    Security and reliability might be two you would maybe didn’t consider, but they are. First starting with security, in client-side rendering, you load all the libraries and static resources, then request data from API and if it maybe fails on the authorization, shows an appropriate error. Problem is that it still loads static resources. With static-site generation, the client will get nothing but immediately receive the error page. Reliability as well. Your page might be dynamic and depend on some API response that doesn’t change. Like blog posts. The typical process would be again, getting resources, and data, generating content, and showing it in the browser. However, sometimes API can be unavailable for many different reasons. With static-site generation, this is not an issue as content is pre-generated and doesn’t depend on other services anymore.

  • SEO Optimization

    Static-site generation reduces load time, reduces the need for server requests after load, and enables better structuring and setting metadata. These are the things taken into account by search engines when ranking web pages.

  • Ease of use

    This one might be a more NextJS-specific benefit. Over time I tried many different single-page application solutions for this, and in my experience, NextJS has the best one so far. Out of the box, during the build, it will generate static content that does not change. You don’t need to do anything. That might be titles, headers, static text, images, or anything else. For the dynamic content loaded from some API or service, there are two functions you can use in your page component. One is the getStaticProps for preparing data that will be used in the generation, and in case your route is dynamic, there is also the getStaticPaths function.

How to Get Started with Static Site Generation in Next.js

For the basic static-site generation with NextJS, you don’t need to do anything. Which is one of the great things about it. During the build time, NextJS will figure out content that does not change, and build content that is sent to the user. The difference comes when you have some content that depends on different data. And that is why there is the getStaticProps function.

export default function Person({ person }) {
  return (
    <>
      Hello {person.firstName} {person.lastName}!
    </>
  )
}

export async function getStaticProps(context) {
  return {
    props: {
      person: { firstName: "John", lastName: "Doe" }
    }, // will be passed to the page component as props
  }
}
Enter fullscreen mode Exit fullscreen mode

In the example above, we have a simple page component Person. This component receives personal details as props that are then used to generate content. For passing those values, we use the getStaticProps function that we need to export in our page component. You may notice that it is an async function. That is because you might need to fetch data from some API or async service.

The above example is a simple static path page, but you might also have dynamic paths that can change depending on something like id. For those, you would need to export another function from your page component. That function is the getStaticPath.

export async function getStaticPaths() {
  return {
    paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
    fallback: false, // can also be true or 'blocking'
  }
}

export async function getStaticProps(context) {
  const id = context.params.id
  return {
    props: {
      person: { firstName: "John " + id, lastName: "Doe " + id }
    }, // will be passed to the page component as props
  }
}
Enter fullscreen mode Exit fullscreen mode

The example above uses the getStaticPath function and returns an array of path parameters for which it will generate content during the build. In the example above it is for id values 1 and 2. Those id values are passed to the getStaticProps function through the function parameter. In the example above that parameter is called context, and it just appends the id value to the name, but in the real-world example it could be something like the id of a person whose data needs to be fetched from the database.

Another parameter you could notice in the getStaticPaths function is fallback with the value false. This value decides if it will also try to generate content during the runtime. In our example, because fallback is set to false, it will create content for path id 1 and 2. If someone tries to access path value 3 it will return the error 404 not found page. In the case of changing that parameter to value true or “blocking”, on request parameter will be passed to the getStaticProps function. That function will try to generate a new page. If it can’t, it returns an error. Otherwise, a new page will be generated on request, just like a server-side generation would. The resulting content is stored on the server and every following request would use that generated content.

Conclusion

The static-side generation has many benefits. Performance, SEO optimization, security, and more. NextJS makes this functionality very easy to use and I hope you got enough insight from this post to help with it. The code used in the examples above can be found in my GitHub repository.


For more, you can follow me on Twitter, LinkedIn, GitHub, or Instagram.

Top comments (0)