Next.js Discord

Discord Forum

Server Action Props + Zod

Answered
Da_v_id posted this in #help-forum
Open in Discord
Avatar
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...
}
Answered by Asian black bear
Finally, it’s how HTTP works - server actions always pass the data as FormData anyways.
View full answer

4 Replies

Avatar
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.
Avatar
Asian black bear
Finally, it’s how HTTP works - server actions always pass the data as FormData anyways.
Answer
Avatar
yea, looking back it sounds like a dumb question, I should use FormData, thank you!