Next.js Course
Next.js
/
Intermediate

Form Actions

Definition

Using Server Actions specifically within HTML `<form>` elements, leveraging native browser behaviors like Progressive Enhancement.

Explain Like I'm New

When you attach a Server Action to a `<form action={...}>`, it works even if the user has JavaScript completely disabled in their browser. Next.js intercepts the native HTML form POST request and handles it beautifully.

Real World Example

A newsletter signup form. You don't need `useState` for the input, you don't need `e.preventDefault()`, and you don't need `fetch`. The browser handles the input, passes a `FormData` object to your Server Action, and you save it to the DB.

Common Use Cases

  • •Robust forms
  • •Progressive Enhancement
  • •Reducing client-side JavaScript

Interactive Example

export default function ContactForm() {
  
  async function submitContact(formData: FormData) {
    'use server';
    // Extract values using the 'name' attribute from the HTML inputs
    const email = formData.get('email');
    const message = formData.get('message');
    
    await sendEmailToAdmin(email, message);
  }

  return (
    <form action={submitContact}>
      {/* The 'name' attribute is critical! It acts as the key in FormData */}
      <input name="email" type="email" required />
      <textarea name="message" required />
      <button type="submit">Send</button>
    </form>
  );
}

Interview Questions

basic

  • What object is automatically passed as the first argument to a Server Action when it is attached to a `<form action>`?

intermediate

  • Do you need to use `e.preventDefault()` when using Server Actions in forms?

Flash Cards

Question

What object?

Click to reveal answer
Answer

A native `FormData` object containing all the input values.

Question

Need preventDefault?

Click to reveal answer
Answer

No! Next.js automatically intercepts the form submission, prevents the default full-page reload, and handles the request via seamless AJAX behind the scenes.