Zod Guide
Learn how to add schema validation to collections using Zod in renoun.
import { Collection } from 'renoun/collections'
import { z } from 'zod'
const frontmatterSchema = z.object({
title: z.string(),
date: z.coerce.date(),
summary: z.string().optional(),
tags: z.array(z.string()).optional(),
})
export const PostsCollection = new Collection<{
default: MDXContent
frontmatter: z.infer<typeof frontmatterSchema>
}>({
filePattern: '*.mdx',
baseDirectory: 'posts',
schema: {
frontmatter: frontmatterSchema.parse,
},
})
Introduction
In this guide, we’ll walk through how to use Zod to add collection schemas to your projects. Using Zod 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 collections work in renoun. If you’re new to collections, check out the Collections Guide. 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 collections 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 = z.object({
title: z.string(),
date: z.coerce.date(),
summary: z.string().optional(),
tags: z.array(z.string()).optional(),
})
Apply to Collection
We can now apply the Zod frontmatterSchema
to your collection using the schema
option in the collection
utility:
import { Collection } from 'renoun/collections'
import type { MDXContent } from 'renoun/mdx'
import { z } from 'zod'
const frontmatterSchema = z.object({
title: z.string(),
date: z.coerce.date(),
summary: z.string().optional(),
tags: z.array(z.string()).optional(),
})
export const PostsCollection = new Collection<{
default: MDXContent
frontmatter: z.infer<typeof frontmatterSchema>
}>({
filePattern: '*.mdx',
baseDirectory: 'posts',
schema: {
frontmatter: frontmatterSchema.parse,
},
})
Now, the frontmatter
field in your collection 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 specific collections.
Conclusion
By using Zod, you can add robust schema validation to your collections 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.