A contact form used to need three pieces: the form, an API route and the fetch call between them. With server actions in the Next.js App Router, the form posts straight to a function that runs on the server.

The basic shape

'use server'

export async function sendMessage(prevState, formData) {
  const email = String(formData.get('email') || '').trim()
  const message = String(formData.get('message') || '').trim()
  if (!email.includes('@')) return { error: 'Please enter a valid email.' }
  if (message.length < 10) return { error: 'Tell me a little more.' }
  await saveMessage({ email, message })
  return { ok: true }
}

On the client, useActionState wires the form to the action and gives you the returned state and a pending flag:

const [state, formAction, pending] = useActionState(sendMessage, {})

Rules worth keeping

  • Validate on the server, always. Browser validation is a convenience; the action is the real gate.
  • Return errors, don't throw them. A returned { error } can be shown next to the form. A thrown error lands on the error page.
  • Check permissions inside every action. An action is a public endpoint. If it changes admin data, verify the session in the action itself, not only in the page or layout.
  • Disable the button while pending so a double click doesn't send two messages.

Progressive enhancement

Because the form uses a real action, it still submits if JavaScript hasn't loaded yet. That matters on slow connections, and it's free.