NextJS

Static Site Generation (SSG) in Next.js - Explained


Introduction to Static Site Generation (SSG)

Static Site Generation (SSG) is a powerful feature in Next.js that allows you to build websites with pre-rendered pages at build time. This means that the HTML for each page is generated during the build process, resulting in fast-loading, SEO-friendly, and highly cacheable websites. In this tutorial, we'll explore SSG in Next.js.

Creating an SSG Page

1. Start by creating a new Next.js project. If you haven't already installed Next.js, you can do so with:

                        npx create-next-app my-ssg-app
                    

2. Create a new page in the `pages` directory, for example, ssg.js:

                        // pages/ssg.js
                        import React from 'react';
                        function SSGPage({ data }) {
                            return (
                                <div>
                                    <h2>Static Site Generation (SSG)</h2>
                                    <p>{data}</p>
                                </div>
                            );
                        }
                        export async function getStaticProps() {
                            // Fetch data from an API or database
                            const response = await fetch('https://api.example.com/data');
                            const data = await response.json();
                            return {
                                props: {
                                    data,
                                },
                            };
                        }
                        export default SSGPage;
                    

In this example, the getStaticProps function is used to fetch data during the build process and pass it as a prop to the component. This page will be pre-rendered as an HTML file during the build.

3. Build your Next.js application using:

                        npm run build
                    

4. Start your Next.js application using:

                        npm run start
                    

5. Access the SSG page by visiting /ssg in your application. The page loads quickly and is SEO-friendly, as it is pre-rendered.

Conclusion

Static Site Generation in Next.js is a game-changer for building fast and highly optimized websites. It allows you to generate pre-rendered HTML pages, resulting in better performance and improved SEO. For more advanced features and use cases, visit the Next.js website.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.