Server Action Props + Zod
Answered
Da_v_id posted this in #help-forum
Da_v_idOP
Hi!
I see many times passing form's inputs as FormData to the server action and perfomr a server-side validation with Zod. I understand the importance of validating the values both client and server side, but why not passing the values as
Like in this case ( I use React Hook Form for client validation);
client
server:
What am I missing? Should i use this signature instead?
I see many times passing form's inputs as FormData to the server action and perfomr a server-side validation with Zod. I understand the importance of validating the values both client and server side, but why not passing the values as
z.infer<typeof whateverSchema>,
?Like in this case ( I use React Hook Form for client validation);
client
const onSubmit = async (values: z.infer<typeof updateUserSchema>) => {
const { success, error } = await updateUserAction(updatedValues); // PASSING IT AS VALID ZOD SCHEMA
}
server:
export const updateUserAction = async (
formData: z.infer<typeof updateUserSchema>,
// TODO: return the updatedProfile if possible
// ): Promise<ServerActionResponse<Tables<"users">>> => {
): Promise<ServerActionResponse> => {
// TODO: add server-side validation
const { success, error, data } = updateUserSchema.safeParse(formData);
if (error) {
return {
success,
error: error.message,
};
}
// Continue logic if successful...
}
What am I missing? Should i use this signature instead?
export const updateUserAction = async (
formData: FormData,
// TODO: return the updatedProfile if possible
// ): Promise<ServerActionResponse<Tables<"users">>> => {
): Promise<ServerActionResponse> => {
// TODO: add server-side validation
const { success, error, data } = updateUserSchema.safeParse(formData);
if (error) {
return {
success,
error: error.message,
};
}
// Continue logic if successful...
}
Answered by Asian black bear
Finally, it’s how HTTP works - server actions always pass the data as FormData anyways.
4 Replies
Asian black bear
Typescript types are just a compile time construct. Without strictly validating nothing stops users from sending malformed data during runtime.
And additionally FormData is a different data type compared to your object that you expect being encoded in it.
Asian black bear
Finally, it’s how HTTP works - server actions always pass the data as FormData anyways.
Answer
Da_v_idOP
yea, looking back it sounds like a dumb question, I should use FormData, thank you!