Understanding Static Site Generation with Next.js

Reading Time: 8 min read

Introduction

Static Site Generation (SSG) is a powerful feature of Next.js that enables you to generate static HTML pages at build time. This approach offers improved performance, better SEO, and enhanced security. In this post, we'll delve into the concept of SSG, its benefits, and how to implement it in your Next.js projects.

What is Static Site Generation?

Static Site Generation (SSG) involves generating HTML pages at build time rather than at runtime. This means that the pages are pre-rendered and served as static files, which can be cached and distributed via a Content Delivery Network (CDN). SSG is ideal for content that doesn't change frequently, such as blogs, documentation, and marketing sites.

Benefits of Static Site Generation

  1. Performance: Static pages load faster as they are served directly from the CDN without server-side processing.
  2. SEO: Pre-rendered HTML ensures that search engines can easily index your content, improving your site's SEO.
  3. Security: With no server-side rendering, there's a reduced attack surface, making your site more secure.
  4. Scalability: Static files can be served to a large number of users with minimal server resources, making it easy to scale.

Implementing SSG in Next.js

Next.js makes it straightforward to implement SSG with the getStaticProps function. This function allows you to fetch data at build time and pass it to your page component.

Example: Blog Post

Let's create a simple blog post page using SSG.

  1. Create a New Page:

    Create a new file pages/posts/[id].js:

    import { useRouter } from 'next/router'
     
    const Post = ({ post }) => {
      const router = useRouter()
     
      if (router.isFallback) {
        return <div>Loading...</div>
      }
     
      return (
        <div>
          <h1>{post.title}</h1>
          <p>{post.body}</p>
        </div>
      )
    }
     
    export async function getStaticPaths() {
      // Fetch the list of posts
      const res = await fetch('https://jsonplaceholder.typicode.com/posts')
      const posts = await res.json()
     
      // Get the paths we want to pre-render based on posts
      const paths = posts.map((post) => ({
        params: { id: post.id.toString() },
      }))
     
      // We'll pre-render only these paths at build time.
      return { paths, fallback: true }
    }
     
    export async function getStaticProps({ params }) {
      // Fetch data for a single post
      const res = await fetch(
        `https://jsonplaceholder.typicode.com/posts/${params.id}`,
      )
      const post = await res.json()
     
      // Pass post data to the page via props
      return { props: { post } }
    }
     
    export default Post
  2. Configure getStaticPaths:

    The getStaticPaths function is used to specify the dynamic routes that should be pre-rendered. It fetches the list of posts and generates the paths based on the post IDs.

  3. Fetch Data with getStaticProps:

    The getStaticProps function fetches data for a specific post at build time and passes it as props to the page component.

Handling Fallback Pages

In the example above, we used fallback: true in the getStaticPaths function. This allows Next.js to generate new pages on-demand when a user navigates to a path that hasn't been pre-rendered yet.

Real-World Example: Blog with SSG

Here’s how you can set up a complete blog using SSG in Next.js:

  1. Set Up the Project:

    npx create-next-app my-blog
    cd my-blog
  2. Create Blog Pages:

    Follow the steps above to create dynamic blog pages using getStaticPaths and getStaticProps.

  3. Add CSS Styling:

    Create a styles/global.css file for global styles and import it in pages/_app.js:

    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }
     
    h1 {
      font-size: 2rem;
      color: #333;
    }
     
    p {
      font-size: 1rem;
      color: #666;
    }
    // pages/_app.js
    import '../styles/global.css'
     
    export default function MyApp({ Component, pageProps }) {
      return <Component {...pageProps} />
    }

Conclusion

Static Site Generation in Next.js offers numerous benefits, from improved performance and SEO to enhanced security and scalability. By leveraging getStaticProps and getStaticPaths, you can easily implement SSG in your projects and deliver a superior user experience. Start experimenting with SSG in Next.js today and see the difference it can make.

For more detailed information, visit the Next.js documentation on Static Site Generation.

Go back Home.