iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚀

Making Zodix Compatible with Both Zod v3 and v4 for React Router v7

に公開

Forking Zodix and Improving It

I've forked the library "Zodix" which performs form and query parameter validation in React Router v7 (formerly Remix), and made it compatible with both Zod v3 and v4, as well as React Router v7. It is published as an NPM package @coji/zodix.

https://github.com/coji/zodix

https://www.npmjs.com/package/@coji/zodix

Why I Forked It

The original Zodix is a useful library, but I encountered a few issues while using it.

1. Migration from Zod v3 to v4

Different projects use different versions of Zod. In large projects, it's not always easy to upgrade due to dependency constraints. Since Zod v3 and v4 are incompatible, I wanted to make both versions usable.

2. Support for React Router v7

As Remix has been integrated into React Router v7, I removed the dependency on the @remix-run packages. This makes it usable with both Remix and React Router v7.

3. Maintenance Status

The original repository has stopped receiving updates, and Issues and PRs are not being addressed. Since I have projects that actually use it, I wanted to be able to maintain it myself.

Implementation Details

Mechanism for Dual Zod v3/v4 Support

The incompatibility between Zod v3 and v4 was the biggest challenge. The type definitions differ between versions, so simple conditional branching wouldn't work.

Ultimately, I decided to provide separate import paths:

// When using Zod v3 (default)
import { zx } from '@coji/zodix'

// When using Zod v4
import { zx } from '@coji/zodix/v4'

In the package.json exports field, specify the corresponding files for each path:

{
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    },
    "./v4": {
      "types": "./dist/v4.d.ts",
      "import": "./dist/v4.js",
      "require": "./dist/v4.cjs"
    }
  }
}

Internally, I prepared separate implementation files for v3 and v4:

src/
├── parsers.v3.ts    # Parser implementation for Zod v3
├── parsers.v4.ts    # Parser implementation for Zod v4
├── schemas.v3.ts    # Helper schemas for Zod v3
├── schemas.v4.ts    # Helper schemas for Zod v4
├── v3.ts           # Exports for v3 (default)
└── v4.ts           # Exports for v4

This provides the following benefits:

  • Complete type safety - Correct types are applied for each version
  • Build-time optimization - Unused version code is not included
  • Easy migration - Just change the import path to migrate from v3 to v4

Dual React Router v7 / Remix Support

I removed the dependency on the @remix-run packages so it works with both:

// Works with Remix
import type { LoaderFunctionArgs } from '@remix-run/node'

export async function loader({ params }: LoaderFunctionArgs) {
  const { postId } = zx.parseParams(params, {
    postId: zx.NumAsString
  })
  // ...
}

// Works with React Router v7
import type { Route } from './+types.posts.$postId'

export async function loader({ params }: Route.LoaderArgs) {
  const { postId } = zx.parseParams(params, {
    postId: zx.NumAsString
  })
  // ...
}

Usage

Installation

npm install @coji/zodix zod

Basic Usage

In a React Router v7 route file:

import { z } from 'zod'
import { zx } from '@coji/zodix' // Zod v3
// import { zx } from '@coji/zodix/v4' // Zod v4

// Parameter validation
export async function loader({ params }: Route.LoaderArgs) {
  const { userId, postId } = zx.parseParams(params, {
    userId: z.string(),
    postId: zx.NumAsString // "123" → 123
  })
  
  // userId and postId are type-safe
  const post = await getPost(userId, postId)
  return { post }
}

// Form data validation
export async function action({ request }: Route.ActionArgs) {
  const data = await zx.parseForm(request, {
    title: z.string().min(1),
    content: z.string().min(10),
    published: zx.CheckboxAsString // "on" → true
  })
  
  // data is fully typed
  await createPost(data)
  return { success: true }
}

Helper Schemas

HTML form and URL parameters are all strings, so conversion to numbers or booleans is often necessary. Zodix provides convenient helper schemas:

// Treat as number
zx.NumAsString    // "3.14" → 3.14
zx.IntAsString    // "42" → 42 (integer only)

// Treat as boolean
zx.BoolAsString      // "true" → true, "false" → false
zx.CheckboxAsString  // "on" → true, undefined → false

Error Handling

Validation errors are automatically handled as 400 errors:

export async function loader({ params }: Route.LoaderArgs) {
  // If postId is not a number, throw a 400 error
  const { postId } = zx.parseParams(
    params,
    { postId: zx.NumAsString },
    { message: "Invalid post ID" }
  )
}

// If custom error handling is needed
export async function action({ request }: Route.ActionArgs) {
  const result = await zx.parseFormSafe(request, {
    email: z.string().email()
  })
  
  if (!result.success) {
    return { error: result.error.flatten() }
  }
  
  // Process with result.data
}

Migration from Zod v3 to v4

Steps to upgrade a project to Zod v4:

  1. Upgrade Zod
npm install zod@^4.0.0
  1. Change the Zodix import path
// Before
import { zx } from '@coji/zodix'

// After
import { zx } from '@coji/zodix/v4'
  1. Update Zod schemas as needed (refer to Zod v4 changelog)

That's all it takes!

Example in a Real Project

It works without issues even in React Router v7's SPA mode. Here's an example from an actual project:

// routes/posts.$postId.edit.tsx
import { zx } from '@coji/zodix/v4'
import type { Route } from './+types.posts.$postId.edit'

export async function action({ params, request }: Route.ActionArgs) {
  const { postId } = zx.parseParams(params, {
    postId: zx.NumAsString
  })
  
  const formData = await zx.parseForm(request, {
    title: z.string().min(1, "Title is required"),
    content: z.string().min(10, "Content must be at least 10 characters"),
    tags: z.array(z.string()).optional()
  })
  
  await updatePost(postId, formData)
  return redirect(`/posts/${postId}`)
}

Summary

By forking Zodix, I achieved compatibility with both Zod v3 and v4 as well as React Router v7. It maintains type safety through separate import paths and allows easy migration.

If you're looking to use form validation in React Router v7, give @coji/zodix a try. Feedback is welcome!

Reference Article

For basic usage of Zodix, please also refer to my previous article:

https://zenn.dev/coji/articles/zodix-introduction

GitHubで編集を提案

Discussion