본문 바로가기

나의 FE피봇이야기/Next

[Next / generateStaticParams() ] 다이나믹 페이지를 pre-Made하기

 

Next 공식 문서

The generateStaticParams function can be used in combination with dynamic route segments to statically generate routes at build time instead of on-demand at request time.

솔직히 무슨 말인지 모르겠음.

 

개인적인 결론으론

1) 서버에서 함수 돌려서 dynamic pages를 다 파악한다.
2) 파악했기 때문에 만들어져 있고 더 빠르게 sever에서 클라이언트로 전송.

 

 

next js

이처럼 작성하라고 함.

 

Chapt 한테 물어봤음.

Understanding generateStaticParams()

In Next.js, generateStaticParams() is used for statically generating paths for dynamic routes at build time. Here's a breakdown of how it works:

  1. Purpose: generateStaticParams() is used to define a list of parameters for dynamic routes. This helps Next.js know which paths to pre-render at build time.
  2. Static Generation: When you have a dynamic route, such as /posts/[id], you use generateStaticParams() to specify which id values to generate pages for statically. This is part of Next.js’s Static Generation feature.
  3. Caching: The pages generated using generateStaticParams() are built at build time and cached as static HTML files. This means they are fast to load and can be served directly from the CDN.
  4. Data Fetching: generateStaticParams() typically involves fetching data from a database, CMS, or API to determine the dynamic route segments that need to be pre-rendered.

 

솔직히 모르겠음.

 

그래서 초딩한테 설명하는 것처럼 해달라고 했음.

generateStaticParams()의 기능

목적: generateStaticParams()는 웹사이트가 게시되기 전에 Next.js가 페이지를 생성할 블로그 게시물을 파악하는 데 도움이 됩니다. 이 작업은 빌드 프로세스 중에 수행됩니다.


작동 방식

글 ID 가져오기: 데이터베이스 또는 API에서 모든 글 ID 목록을 가져오는 함수를 작성합니다.
경로 생성: 이 ID를 사용하여 Next.js에 "이 특정 URL에 대한 페이지를 만들어 주세요."라고 말합니다.

 

 

아래 글은 참조

Sure! Let's break it down in a simple way:

### Imagine You Have a Blog

1. **Blog Posts**: You have a blog with many posts. Each post has a unique ID. For example:
   - Post 1: ID is "1"
   - Post 2: ID is "2"
   - Post 3: ID is "3"

2. **Dynamic URLs**: You want each post to have its own URL, like:
   - `myblog.com/posts/1`
   - `myblog.com/posts/2`
   - `myblog.com/posts/3`

### What `generateStaticParams()` Does

- **Purpose**: `generateStaticParams()` helps Next.js know which blog posts to create pages for **before** the website is even live. This is done during the build process.

### How It Works

1. **Fetch Post IDs**: You write a function to get a list of all the post IDs from a database or an API.
2. **Generate Paths**: Using these IDs, you tell Next.js, "Please create pages for these specific URLs."

### Step-by-Step Example

Let's go step-by-step with a simple analogy:

#### 1. Collecting IDs

Imagine you have a list of all post IDs:
```javascript
const postIDs = ["1", "2", "3"];
```

#### 2. Creating Paths

You then tell Next.js to create pages for these IDs:
```javascript
function generateStaticParams() {
  // This will generate paths like:
  // /posts/1
  // /posts/2
  // /posts/3
  return postIDs.map(id => ({
    params: { id: id }
  }));
}
```

#### 3. Building Pages

Next.js will take this list and create HTML pages for each post. So, during the build, it creates:
- `posts/1.html`
- `posts/2.html`
- `posts/3.html`

### Complete Example Code

Here's how it looks in a Next.js file:

```javascript
// pages/posts/[id].js

// This function generates the paths for all posts
export async function generateStaticParams() {
  // Simulate fetching post IDs from an API or database
  const postIDs = ["1", "2", "3"];

  // Generate paths for each post ID
  return postIDs.map(id => ({
    params: { id: id }
  }));
}

// This component renders a post based on its ID
export default function Post({ post }) {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
}

// This function fetches the data for each post
export async function getStaticProps({ params }) {
  // Simulate fetching post data from an API
  const posts = {
    "1": { title: "Post 1", content: "This is the first post." },
    "2": { title: "Post 2", content: "This is the second post." },
    "3": { title: "Post 3", content: "This is the third post." }
  };

  return {
    props: { post: posts[params.id] }
  };
}
```

### Recap

- **generateStaticParams()**: Tells Next.js which pages (URLs) to create before going live.
- **Benefit**: Makes your website faster because these pages are pre-made.
- **How**: You list out the IDs for the dynamic pages, and Next.js builds them during the build process.

I hope this simplifies it for you!