> For the complete documentation index, see [llms.txt](https://tech.x2bee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tech.x2bee.com/dev-guide/pjt-prepare/publish-your-docs/store-front-framewok-next.js/02./2.-json-schema-validator-zod.md).

# 2. Json schema validator : Zod

이 문서는 REST API로부터 받은 JSON 데이터의 유효성을 검사하기 위한 필수 패키지인 Zod의 사용법을 안내합니다.

***

## 설치

Zod는 runtime dependency로 사용하므로 --save-dev가 아닌 바로 install 합니다.

{% hint style="info" %}
Zod는 런타임 의존성입니다. 개발 의존성(devDependency)으로 설치하지 마세요.
{% endhint %}

{% code title="설치" %}

```bash
pnpm add zod
```

{% endcode %}

## 사용

{% code title="예제: Product 유효성 검사 (React 컴포넌트)" %}

```javascript
import { z } from 'zod';

const productJson = {
  name: 'jeans',
  price: 100,
};

const productSchema = z.object({
  name: z.string(),
  price: z.number().positive(), // 양수, 음수 구별 가능
});

// type Product = z.infer<typeof productSchema>;

const Test1 = () => {
  const validateProduct = productSchema.safeParse(productJson);
  console.log('validateProduct', validateProduct);

  if (validateProduct.success === false) {
    console.error(validateProduct.error.message);
    return;
  }

  return <div>Test1</div>;
};

export default Test1;
```

{% endcode %}

{% stepper %}
{% step %}

### infer

위 코드는 예시를 위해 fetch를 통해 json을 가지고오지 않고 바로 하드코딩한 예입니다.

만약 fetch를 통해 가져온다면 미리 type(interface)을 지정해줘야 하는데, 이러면 validation에서 한 번 더 입력해줘야 하니 interface를 두 번 작업해야되는 번거로움이 생깁니다. 그래서 위에서처럼,

type Product = z.infer;

zod로 한 번 type을 검토하고, 위 코드처럼 한 줄로 TypeScript에서 type을 지정해줄 수 있습니다.
{% endstep %}

{% step %}

### safeParse

위 코드처럼 safeParse를 해주고 validateProduct를 출력하면,

validateProduct { success: true, data: { name: 'jeans', price: 100 } }

success라는 키가 true / false인지 알려줍니다.
{% endstep %}
{% endstepper %}

## 테스트

이제 위에 하드코딩된 Json의 name을 → id 로 변경해주면 콘솔 출력은 다음과 같이 됩니다:

validateProduct { success: false, error: \[Getter] }

ZodError 예시: { "code": "invalid\_type", "expected": "string", "received": "undefined", "path": \[ "name" ], "message": "Required" }

validateProduct.success는 false가 되고, Required 필드인 name이 invalid type이라고 표시됩니다.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://tech.x2bee.com/dev-guide/pjt-prepare/publish-your-docs/store-front-framewok-next.js/02./2.-json-schema-validator-zod.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.
