How do you submit a form directly to a server action in Next.js without writing any client side JavaScript?
Short answer
You pass your server action function directly to the form element's action attribute, and Next.js automatically handles collecting the form data and sending it to your server action, even working correctly before any client side JavaScript has loaded, thanks to progressive…
Advertisement
AModel answer
You pass your server action function directly to the form element's action attribute, and Next.js automatically handles collecting the form data and sending it to your server action, even working correctly before any client side JavaScript has loaded, thanks to progressive enhancement.
// app/contact/page.js
import { submitContact } from './actions';
export default function ContactPage() {
return (
<form action={submitContact}>
<input name="email" type="email" required />
<button type="submit">Send</button>
</form>
);
}Real-world example
A simple contact form submits directly to a server action, working correctly even for users on slow connections where the page's JavaScript has not fully loaded yet.
Likely follow-ups
- What does progressive enhancement mean in the context of forms?
- How do you read the submitted values inside the server action?
Related topics