This example shows how you can build upload forms with Next.js and Server Actions, which focus on advanced server-side validation.
-
onSumit
is most recommend way, we can easily usezod
to validate the form both on the client and the server without third-party react form library. -
useFormState
is most progressive enhancement way, we can validate the form event when JavaScript is disable on our browsers, but there is no client-size form validation any more. -
useForm
is most UX way, we can easily develop the form page withreact-hook-form
, but there is no server-side form validation any more. On the other hand, it will spend you extra time to refactor the form, sometimes it's not a better choice for simple pages.
- The submitted file form data as Server Action handler argument should always be a
Formdate
instance, otherwise you'll meet the below error:
Error: Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.
When invoked in a form, the action automatically receives the formData object. If you have validated the upload form with use react-hook-form
on the client-side, the formData object will be unwrapped automatically, we can wrap it again manually to find a problem solution. e.g.:
const formData = new FormData()
formData.append('name', values.name)
formData.append('picture', values.picture)
Or simply use the second event param of SubmitHandler
if there are many form fields:
const onSubmit: SubmitHandler<UploadValue> = async (
_values, event
) => {
const formData = new FormData(event.currentTarget)
}
- If you got the following error when using
z.instanceof(File)
:
Error: File is not defined
Check you node version, the iisue has been fixed from 20x.
Deploy it to the cloud with Vercel (Documentation).