> 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/developer-guide-en/pjt-prepare/publish-your-docs/store-front-framework-next.js/02.-coding-guide-and-essential-packages/2.-json-schema-validator-zod.md).

# 2. Json schema validator : Zod

This document guides you through using Zod, an essential package for validating JSON data received from a REST API.

***

## Installation

Since Zod is used as a runtime dependency, install it directly rather than with --save-dev.

{% hint style="info" %}
Zod is a runtime dependency. Do not install it as a devDependency.
{% endhint %}

{% code title="Installation" %}

```bash
pnpm add zod
```

{% endcode %}

## Usage

{% code title="Example: Product Validation (React Component)" %}

```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

The code above is a hardcoded example for illustration purposes, rather than fetching the JSON via fetch.

If you fetch it via fetch, you would need to specify a type (interface) in advance, and this would mean you have to write the interface a second time in the validation, which is a hassle. So as shown above,

type Product = z.infer;

you can first review the type with zod, and then, as in the code above, specify the type in TypeScript in a single line.
{% endstep %}

{% step %}

### safeParse

If you run safeParse as in the code above and print validateProduct,

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

it tells you whether the success key is true or false.
{% endstep %}
{% endstepper %}

## Testing

Now, if you change the name in the hardcoded JSON above to id, the console output will be as follows:

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

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

validateProduct.success becomes false, and it indicates that name, which is a required field, has an invalid type.
