Skip to content

Getting type error when passing FormData as a param in createServerFn validator, handler or middleware #2832

@ricardoraposo

Description

@ricardoraposo

Which project does this relate to?

Router

Describe the bug

Receiving type error when passing FormData as param of a server function, as shown in the "Server Functions" docs page after "Getting Started"

Image

Your Example Website or App

No link

Steps to Reproduce the Bug or Issue

As shown in the docs page, below:
https://tanstack.com/router/latest/docs/framework/react/start/server-functions

Create a server function using createServerFn(), call one of the available methods ("validator", "handler", "middleware")

export const handleSubmit = createServerFn({ method: "POST" })
  .validator((data: FormData) => {
    if (!(data instanceof FormData)) {
      throw new Error("Invalid form data")
    }
    const name = data.get("name")
    const age = data.get("age")

    if (!name || !age) {
      throw new Error("Name and age are required")
    }

    return {
      name: name.toString(),
      age: Number(age.toString()),
    }
  })
  .handler(async ({ data: { name, age } }) => {
    return `Hello, ${name}! You are ${age} years old.`
  })

export function Form() {
  return (
    <form
      onSubmit={async (event) => {
        event.preventDefault()
        const formData = new FormData(event.target as HTMLFormElement)
        const response = await handleSubmit({ data: formData })
        console.log(response)
      }}
      className="flex flex-col gap-4 p-4"
    >
      <input name="name" />
      <input name="age" />
      <button
        className="bg-blue-500 text-white px-4 py-2 rounded"
        type="submit"
      >
        Submit
      </button>
    </form>
  )
}

Expected behavior

FormData should not throw an error, as it can be sent in a POST request because it can be parsed when sent as a multipart/form-data request

Screenshots or Videos

Image

Platform

  • OS: Linux/PopOS
  • Version: {
    "@tanstack/react-router": "^1.82.2",
    "@tanstack/start": "^1.82.6",
    }

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    typesChanges to the typescript types

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions