Zod Guide
Learn how to add schema validation to your file system using Zod in renoun.
import { Directory, withSchema } from 'renoun/file-system'
import { z } from 'zod'
const frontmatterSchema = {
title: z.string(),
date: z.date(),
summary: z.string().optional(),
tags: z.array(z.string()).optional(),
}
const posts = new Directory({
path: 'posts',
include: '*.mdx',
loaders: {
mdx: withSchema(
{ frontmatter: frontmatterSchema },
(path) => import(`@/posts/${path}.mdx`)
),
},
})
Introduction
In this guide, we’ll walk through how to use Zod to add schema validation to your file system. Using Valibot ensures that your targeted files conform to an expected structure, providing type safety and validation.
Before You Begin
Before you start, make sure you have a basic understanding of how the File System API works in renoun. We’ll also be using MDX files in this guide, so make sure you’re familiar with the MDX Guide as well.
Using Zod
Zod is a TypeScript-first schema validation library with static type inference. Let’s look at how you can use Zod to add schema validation to your file system in renoun.
Install
First, install zod
using your package manager:
Define Schema
Now, we’ll create a schema using zod
for the front matter of an MDX file:
import { z } from 'zod'
const frontmatterSchema = {
title: z.string(),
date: z.date(),
summary: z.string().optional(),
tags: z.array(z.string()).optional(),
}
Apply to a Directory
We can now apply the Zod frontmatterSchema
to your Directory
using the withSchema
helper:
import { Directory, withSchema } from 'renoun/file-system'
import { z } from 'zod'
const frontmatterSchema = {
title: z.string(),
date: z.date(),
summary: z.string().optional(),
tags: z.array(z.string()).optional(),
}
const posts = new Directory({
path: 'posts',
include: '*.mdx',
loaders: {
mdx: withSchema(
{ frontmatter: frontmatterSchema },
(path) => import(`@/posts/${path}.mdx`)
),
},
})
Now, the frontmatter
field in your MDX files will be validated against the frontmatterSchema
we defined using Zod. If the data does not match the schema, an error will be thrown.
Beyond Front Matter
While the example in this guide focused on validating front matter in MDX files, the same approach can be applied to validate any kind of export within a file. Whether you need to enforce a specific structure for other metadata, content fields, or custom data exports, Zod provides the flexibility to define schemas that fit your file system requirements.
Conclusion
By using Zod, you can add robust schema validation to your file system in renoun. This ensures that your data is always in the expected format, making your application more reliable and easier to maintain.
For more information, refer to the Zod documentation.