Back to Snippets
Next.jsTypeScript

Next.js Server Action Form

A form that uses server actions for submission with validation.

nextjsformserver actionvalidation
class=class="text-emerald-400">"text-emerald-400">'use server'

import { z } from class=class="text-emerald-400">"text-emerald-400">'zod'

const ContactSchema = z.object({
  name: z.string().min(2, class=class="text-emerald-400">"text-emerald-400">'Name must be at least 2 characters'),
  email: z.string().email(class=class="text-emerald-400">"text-emerald-400">'Invalid email address'),
  message: z.string().min(10, class=class="text-emerald-400">"text-emerald-400">'Message must be at least 10 characters'),
})

export type FormState = {
  success: boolean
  errors?: Record<string, string[]>
  message?: string
}

export async function submitContact(
  _prevState: FormState,
  formData: FormData
): Promise<FormState> {
  const raw = {
    name: formData.get(class=class="text-emerald-400">"text-emerald-400">'name') as string,
    email: formData.get(class=class="text-emerald-400">"text-emerald-400">'email') as string,
    message: formData.get(class=class="text-emerald-400">"text-emerald-400">'message') as string,
  }

  const result = ContactSchema.safeParse(raw)
  if (!result.success) {
    return { success: false, errors: result.error.flatten().fieldErrors }
  }

  class=class="text-emerald-400">"text-gray">// Save to database or send email
  return { success: true, message: class=class="text-emerald-400">"text-emerald-400">'Message sent successfully!' }
}

How to Use

Import the action and use with useActionState: const [state, formAction] = useActionState(submitContact, { success: false }). Pass formAction as the form's action prop. Display state.errors for validation feedback.

Related Technology

Next.js

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call