Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions astro.sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ export const sidebar = [
'reference/modules/astro-i18n',
'reference/modules/astro-middleware',
'reference/modules/astro-transitions',
'reference/modules/astro-zod',
],
}),
group('reference.other', {
Expand Down
4 changes: 2 additions & 2 deletions src/content/docs/en/guides/actions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Astro Actions allow you to define and call backend functions with type-safety. A

Use actions instead of API endpoints for seamless communication between your client and server code and to:

- Automatically validate JSON and form data inputs using [Zod validation](https://zod.dev/?id=primitives).
- Automatically validate JSON and form data inputs using [Zod validation](/en/reference/modules/astro-zod/).
- Generate type-safe functions to call your backend from the client and even [from HTML form actions](#call-actions-from-an-html-form-action). No need for manual `fetch()` calls.
- Standardize backend errors with the [`ActionError`](/en/reference/modules/astro-actions/#actionerror) object.

Expand Down Expand Up @@ -73,7 +73,7 @@ Follow these steps to define an action and call it in a `script` tag in your Ast
}
```

3. Use the `defineAction()` utility to define a `getGreeting` action. The `input` property will be used to validate input parameters with a [Zod](https://zod.dev) schema and the `handler()` function includes the backend logic to run on the server.
3. Use the `defineAction()` utility to define a `getGreeting` action. The `input` property will be used to validate input parameters with a [Zod schema](/en/reference/modules/astro-zod/#common-data-type-validators) and the `handler()` function includes the backend logic to run on the server.

```ts ins={5-12} title="src/actions/index.ts"
import { defineAction } from 'astro:actions';
Expand Down
36 changes: 3 additions & 33 deletions src/content/docs/en/guides/content-collections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ Schemas also power Astro's automatic TypeScript typings for your content. When y
In order for Astro to recognize a new or updated schema, you may need to restart the dev server or [sync the content layer](/en/reference/cli-reference/#astro-dev) (<code>s + enter</code>) to define the `astro:content` module.
:::

Every frontmatter or data property of your collection entries must be defined using a Zod data type:
Every frontmatter or data property of your collection entries must be defined using a [Zod data type](/en/reference/modules/astro-zod/#common-data-type-validators):

```ts title="src/content.config.ts" {6-11,15-19}
import { defineCollection, z } from 'astro:content';
Expand Down Expand Up @@ -241,41 +241,11 @@ Astro uses [Zod](https://github.com/colinhacks/zod) to power its content schemas

To use Zod in Astro, import the `z` utility from `"astro:content"`. This is a re-export of the Zod library, and it supports all of the features of Zod.

```ts
// Example: A cheatsheet of many common Zod datatypes
import { z, defineCollection } from 'astro:content';

defineCollection({
schema: z.object({
isDraft: z.boolean(),
title: z.string(),
sortOrder: z.number(),
image: z.object({
src: z.string(),
alt: z.string(),
}),
author: z.string().default('Anonymous'),
language: z.enum(['en', 'es']),
tags: z.array(z.string()),
footnote: z.string().optional(),

// In YAML, dates written without quotes around them are interpreted as Date objects
publishDate: z.date(), // e.g. 2024-09-17

// Transform a date string (e.g. "2022-07-08") to a Date object
updatedDate: z.string().transform((str) => new Date(str)),

authorContact: z.string().email(),
canonicalURL: z.string().url(),
})
})
```

<ReadMore>See [Zod's README](https://github.com/colinhacks/zod) for complete documentation on how Zod works and what features are available.</ReadMore>
<ReadMore>See the [`z` utility reference](/en/reference/modules/astro-zod/) for a cheatsheet of common datatypes and to learn how Zod works and what features are available.</ReadMore>

##### Zod schema methods

All [Zod schema methods](https://zod.dev/?id=schema-methods) (e.g. `.parse()`, `.transform()`) are available, with some limitations. Notably, performing custom validation checks on images using `image().refine()` is unsupported.
All [Zod schema methods](/en/reference/modules/astro-zod/#using-zod-methods) (e.g. `.parse()`, `.transform()`) are available, with some limitations. Notably, performing custom validation checks on images using `image().refine()` is unsupported.

#### Defining collection references

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/en/reference/modules/astro-actions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Return values are parsed using the [devalue library](https://github.com/Rich-Har
**Type:** `ZodType | undefined`
</p>

An optional property that accepts a Zod validator (e.g. Zod object, Zod discriminated union) to validate handler inputs at runtime. If the action fails to validate, [a `BAD_REQUEST` error](#actionerror) is returned and the `handler` is not called.
An optional property that accepts a [Zod validator](/en/reference/modules/astro-zod/#common-data-type-validators) (e.g. Zod object, Zod discriminated union) to validate handler inputs at runtime. If the action fails to validate, [a `BAD_REQUEST` error](#actionerror) is returned and the `handler` is not called.

If `input` is omitted, the `handler` will receive an input of type `unknown` for JSON requests and type `FormData` for form requests.

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/en/reference/modules/astro-content.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ A `loader` is either an object or a function that allows you to load data from a
<Since v="2.0.0" />
</p>

`schema` is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use [a Zod validator](https://github.com/colinhacks/zod).
`schema` is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use [a Zod validator](/en/reference/modules/astro-zod/#common-data-type-validators).

[See the `Content Collection` guide](/en/guides/content-collections/#defining-the-collection-schema) for example usage.

Expand Down
120 changes: 120 additions & 0 deletions src/content/docs/en/reference/modules/astro-zod.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
---
title: Zod API Reference
sidebar:
label: 'astro/zod'
i18nReady: true
tableOfContents:
minHeadingLevel: 2
maxHeadingLevel: 6
---
import ReadMore from '~/components/ReadMore.astro';

[Zod](https://github.com/colinhacks/zod) is a TypeScript-based schema declaration and validation library. This allows you to define schemas you can use to validate data and transform data, from a simple type (e.g. `string`, `number`) to complex data structures (e.g. nested objects).

The `astro/zod` module exposes a re-export of Zod that gives you access to all the features of Zod v3. By using this module, you do not need to install Zod yourself. This also ensures that your project uses the same API versions as Astro when using features such as [Content Collections](/en/guides/content-collections/) or [Actions](/en/guides/actions/).

<ReadMore>See [Zod v3 website](https://v3.zod.dev/) for complete documentation on how Zod works and what features are available.</ReadMore>

## Imports from `astro/zod`

```ts
import { z } from 'astro/zod';
```

### `z`

<p>

**Type:** `object`
</p>

The `z` utility gives you access to validators for a wide range of data types, methods and types for working with your data.

<ReadMore>Learn more about the `z` utility in [Zod documentation](https://v3.zod.dev/?id=basic-usage)</ReadMore>

#### Common data type validators

With Zod, you can validate any type of data, such as [primitives](https://v3.zod.dev/?id=primitives), [objects](https://v3.zod.dev/?id=objects), [arrays](https://v3.zod.dev/?id=arrays) and more.

The following example shows a cheatsheet of many common Zod data types to create a `user` schema:

```ts
import { z } from 'astro/zod';

const user = z.object({
username: z.string(),
name: z.string().min(2),
email: z.string().email(),
role: z.enum(["admin", "editor"]),
language: z.enum(["en", "fr", "es"]).default("en"),
hobbies: z.array(z.string()),
age: z.number(),
isEmailConfirmed: z.boolean(),
inscriptionDate: z.date(),
website: z.string().url().optional(),
});
```

#### Extracting a Typescript type

Zod allows you to create a Typescript type from any schema [using Zod type inference](https://v3.zod.dev/?id=type-inference). This can be useful for describing an expected data structure when [defining component props](/en/guides/typescript/#component-props).

The following example create a `User` type based on the previous schema:

```ts
type User = z.infer<typeof user>;

/* The `User` type will be:
* type User = {
* username: string;
* name: string;
* email: string;
* role: "admin" | "editor";
* language: "en" | "fr" | "es";
* hobbies: string[];
* age: number;
* isEmailConfirmed: boolean;
* inscriptionDate: Date;
* website?: string | undefined;
* }
*/
```

#### Using Zod methods

Zod provides various [schema methods](https://v3.zod.dev/?id=schema-methods) to customize error messages, transform data, or create custom validation logics.

```ts
// Customize the error message
const nonEmptyStrings = z.string().array().nonempty({
message: "Can't be empty!",
});

// Validate a data from a schema
nonEmptyStrings.parse([]); // will throws our custom error

// Create an object from a URL for a decorative img
const decorativeImg = z.string().transform((value) => {
return { src: value, alt: "" };
});

// Create a custom validator and error message for a string
const constrainedString = z
.string()
.refine((val) => val.length > 0 && val.length <= 255, {
message: "Must be between 1 and 255 characters.",
});
```

### Individual imports

Alternatively, you can import all the Zod validators, methods and types available in the [`z` utility](#z) directly from the module.

The following example imports `coerce` to create a `Date` object from a date string:

```ts
import { coerce } from 'astro/zod';

const publishedOn = coerce.date();
const publicationDate = publishedOn.parse("2025-12-03");
```