`withValidator({ body })` rejects the multipart bodies that `useForm` and `action()` send for files

オープン
#679 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
35/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
react, typescript
領域
api, backend

調査の方向性

Start in runtime/validator.ts, where the body slot calls c.req.json(), and in objectToFormData() in pages/navigation-engine.ts, which encodes the multipart fields. The open design question is whether non-file values should be coerced in the schema or sent as one JSON part, so settle that before editing. Done means a multipart action with a File reaches the handler with a typed body and fills form.errors on schema failure, while JSON requests behave as before.

索引モデルが issue の本文から書いたものです。

説明

Summary

When the data holds a File, Blob or FileList, useForm and action() send it as multipart/form-data (hasFiles() → objectToFormData() in pages/navigation-engine.ts). withValidator({ body }) only calls c.req.json() (runtime/validator.ts), so it answers 400 {"error":"Invalid JSON body"} before the handler runs. Void's client and its validator don't agree on the body format.

The file uploads guide avoids this by skipping withValidator and calling c.req.parseBody(). That gives up what the validator gives every other action:

  • a typed body in the handler,
  • form.errors filled from the schema's issues,
  • useForm data typed from the schema (without a validator it falls back to Record<string, unknown>).
Reproduction
// pages/photos.server.ts
import { defineHandler } from 'void';
import { z } from 'zod';

export const action = defineHandler.withValidator({
  body: z.object({ title: z.string().min(1), photo: z.instanceof(File) }),
})(async (c, { body }) => {
  // never reached when a file is attached
});
// pages/photos.tsx: the upload form from the guide
const form = useForm('/photos', { title: '', photo: null as File | null });

Pick a file and submit. The client posts FormData, and the action answers 400 {"error":"Invalid JSON body"} without running the handler. form.errors stays {}, and form.error is a generic VoidActionError: Action failed with 400 Bad Request. With no file, the client sends JSON, and the validator fills form.errors as expected.

Proposal
  • Read form bodies in the body slot. For multipart/form-data and application/x-www-form-urlencoded, read the body with c.req.formData() instead of c.req.json(), and pass File values through to the schema.
  • Undo objectToFormData()'s encoding, so the schema sees the shape the client sent: a[b] back into nested objects, a[0] and a[] back into arrays. Otherwise a nested field arrives as a flat 'profile[name]' key.
  • Keep scalar types, or document that they're lost. The client sends booleans as '1'/'0', numbers as strings, null as '' and dates as ISO strings, so a schema written for the JSON body fails on the multipart one. Either document that the schema needs coercion, or have the client send the non-file values as one JSON part and only the files as separate parts, so the server can rebuild the exact object and one schema works for both encodings.
Prior art
  • Hono, which Void builds on: validator('form', …) validates parseBody() output, alongside validator('json', …).
  • Next.js: server actions receive FormData, files included, and libraries like Conform and zod-form-data validate it with a schema.
  • SvelteKit: Superforms validates request.formData(), files included, with the same schema as the client.
Workaround
// pages/photos.server.ts
import { defineHandler, ValidationError } from 'void/handler';
import { z } from 'zod';

const photoSchema = z.object({ title: z.string().min(1), photo: z.instanceof(File) });

export const action = defineHandler(async (c) => {
  const result = photoSchema.safeParse(await c.req.parseBody());
  if (!result.success) {
    throw new ValidationError(
      Object.fromEntries(result.error.issues.map((issue) => [issue.path.join('.'), issue.message])),
    );
  }
  // result.data is typed here, but useForm's data and errors aren't
});
Environment
  • void 1.5.0
  • @void/react 1.5.0
主要言語
TypeScript
スター
627
フォーク
66
平均マージ
14時間 38分
マージ済み PR(30日)
179

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

voidzero-dev/void のほかの issue

voidzero-dev/void の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。