#Server Action Props + Zod

6 messages · Page 1 of 1 (latest)

acoustic mason
#

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 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...
}
echo skyBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

desert rune
#

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.

#

Finally, it’s how HTTP works - server actions always pass the data as FormData anyways.

acoustic mason
#

yea, looking back it sounds like a dumb question, I should use FormData, thank you!