# 일반적인 Next.js 블로그

## 컨텐츠 데이터 관리

`md`라는 확장자를 갖는 파일에 마크다운 형태로 글을 작성합니다. 해당 파일은 크게 두가지 영역을 갖습니다.&#x20;

### Front Matter

상단에 3개의 하이픈으로 구분된 영역에 작성되는 값입니다. 이 형식으로 지정된 값은 이후 메타데이터 정보로 활용됩니다. 아래의 예시에서는 제목, 설명, 날짜 정보가 작성되었습니다.

```markdown
---
title: 'post title'
description: 'this is post description'
date: '2024-08-15'
---
```

### Content

Front Matter 아래에는 실제 글의 내용이 담깁니다. 마크다운 형태로 작성합니다. 이렇게 작성된 파일이 파싱 함수에 의해 분석됩니다.

```markdown
# post title
hello world!
```

### Parsing

예시에서는 `getPostData`라는 이름을 가진 함수입니다.&#x20;

```typescript
export async function getPostData(id) {
  const fullPath = path.join(postsDirectory, `${id}.md`);
  const fileContents = fs.readFileSync(fullPath, 'utf8');
  
  const matterResult = matter(fileContents);
  
  const processedContent = await remark()
    .use(html)
    .process(matterResult.content);
  
  const contentHtml = processedContent.toString();
  
  return {
    id,
    contentHtml,
    ...matterResult.data, 
  };
}
```

`getPostData`는 파일시스템에 접근해 마크다운 파일을 읽어 날것의 데이터 찾아냅니다.&#x20;

이 데이터를 `matter`라는 함수에 전달합니다. 해당 함수는 `gray-matter`와 같은 라이브러리에서 제공하는 함수입니다. 앞서 보셨던 마크다운 파일에서 Front Mattter와 Content 영역을 나눠주는 역할을 합니다. 그렇게 반환된 값은 `matterResult`에 저장됩니다.

`matterResult`에 있는 content는 마크다운 형태로 존재합니다. 이제 브라우저에 전달하기 전에 HTML로 전환하는 과정을 거칩니다. 코드를 보시면 `remark`라는 라이브러리와 플러그인을 이용해서 마크다운을 HTML로 파싱하고 있습니다.

이렇게 만들어진 HTML 문자열과 메타데이터 등의 값이 `getPostData`의 결과값으로 반환됩니다.

## 라우팅과 렌더링

보통 Dynamic Routes 기법을 사용합니다. `pages/post/[id].tsx` 와 같은 형태로 파일을 만듭니다. 대괄호에 담긴 id가 게시글 조회의 단서로 사용됩니다.

렌더링은 정적 사이트 생성, SSG를 사용합니다.&#x20;

```typescript
export async function getStaticProps({ params }) {
  const postData = await getPostData(params.id);
  
  return {
    props: {
      postData,
    },
  };
}
```

`getStaticProps`라는 함수에서 정적으로 사용할 데이터를 조회합니다. 앞서 컨텐츠 데이터 관리에서 살펴 본 `getPostData` 함수가 등장하네요. 파라미터로 전달된 id 값을 전달하면 게시글의 데이터를 찾아냅니다. 그 데이터를 반환하구요.

반환된 값을 UI 컴포넌트에서 활용하게 됩니다.&#x20;

```tsx
export default function Post({ postData }) {
  return (
    <Layout>
      {postData.title}
      <br />
      {postData.id}
      <br />
      {postData.date}
      <br />
      <div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />
    </Layout>
  );
}
```

`getPostData`에서 만들어낸 `contentHtml`을 `dangerouslySetInnerHTML`에 그대로 넣어 사용합니다. 이게 일반적인 Next.js 블로그의 라우팅, 렌더링 방식입니다.

## 메타데이터

작성된 마크다운 파일에서 Front Matter 영역을 작성합니다. `getPostData`에서 만들어낸 Front Matter 영역을 Next.js에서 제공하는 `Head` 컴포넌트에 `title`, `meta` 태그로 넣으면 메타데이터로 인식됩니다.

```html
<Head>
  <title>{title}</title>
  <meta name="description" content={description} />
  <meta name="date" content={date} />
</Head>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.hajoeun.dev/friendly-next-js/part-3-next.js/undefined-2/next.js.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
