ReasonJun

Next.js : How to bring data in Nextjs (getStaticPaths) (SSG) 본문

Frontend/Next.js

Next.js : How to bring data in Nextjs (getStaticPaths) (SSG)

ReasonJun 2023. 6. 17. 02:30
728x90

getStaticPaths

getStaticPaths is a Next.js function that allows you to pre-generate a list of paths for your pages. This can be useful for pages that have dynamic routes, such as blog posts or product pages.

The getStaticPaths function is called once during the build process, and the results are cached. This means that the next time a user visits a page, the pre-generated list of paths will be used to determine which pages should be pre-rendered.

The getStaticPaths function takes two arguments:

  • params: An object that contains the URL parameters for the page.
  • context: An object that contains information about the current build context.

The getStaticPaths function must return an object with the following properties:

  • paths: An array of paths that should be pre-rendered.
  • fallback: A boolean that specifies whether or not to serve a fallback page if a path is not found.

Here is an example of how to use getStaticPaths:

export const getStaticPaths = async (params) => {
  const posts = await fetch(`/api/posts`).then((res) => res.json());

  const paths = posts.map((post) => {
    return {
      params: {
        slug: post.slug,
      },
    };
  });

  return {
    paths,
    fallback: true,
  };
};

In this example, the getStaticPaths function fetches a list of posts from an API and returns an array of paths that should be pre-rendered. The fallback property is set to true, so if a path is not found, a fallback page will be served.

The getStaticPaths function is a powerful tool that can help you improve the performance of your Next.js applications. If you are working with pages that have dynamic routes, then getStaticPaths is a great option.

Here are some additional benefits of using getStaticPaths:

  • Performance: Pre-generating a list of paths can improve performance, as the browser does not need to fetch the paths on each request.
  • SEO: Pre-generating a list of paths can help improve your website's SEO.
  • Scalability: getStaticPaths can be used to scale your application by generating static pages for different audiences or devices.

If you are looking for a way to improve the performance, SEO, and scalability of your Next.js applications, then getStaticPaths is a great option.

 

🚨

SSG does not work properly in the development environment. It works like an SSR. Therefore, in order to see the SSG properly, you need to build it.

 

=> Even when you refresh the page the page doesn't change.

728x90
Comments