Form actions with server functions let you handle form data directly on the server. This makes your app faster and more secure by avoiding extra client-side code.
Form actions with server functions in NextJS
import { redirect } from 'next/navigation' export async function action(formData: FormData) { // process formData here return redirect('/thank-you') } export default function Page() { return ( <form action={action} method="post"> <input name="name" type="text" required /> <button type="submit">Send</button> </form> ) }
The action function runs on the server when the form is submitted.
Use formData.get('fieldName') to access form values inside the action.
export async function action(formData: FormData) { const name = formData.get('name') console.log('Name:', name) return new Response('Form received') } export default function Page() { return ( <form action={action} method="post"> <input name="name" type="text" /> <button type="submit">Submit</button> </form> ) }
import { redirect } from 'next/navigation' export async function action(formData: FormData) { const email = formData.get('email') // Save email to database here return redirect('/welcome') } export default function Page() { return ( <form action={action} method="post"> <input name="email" type="email" required /> <button type="submit">Register</button> </form> ) }
This is a simple contact form. When submitted, the message is sent to the server function action. The server logs the message and then redirects the user to a thank-you page.
import { redirect } from 'next/navigation' export async function action(formData: FormData) { const message = formData.get('message') console.log('Received message:', message) // Here you could save the message to a database return redirect('/thank-you') } export default function ContactForm() { return ( <main> <h1>Contact Us</h1> <form action={action} method="post"> <label htmlFor="message">Your Message:</label> <textarea id="message" name="message" required rows={4} cols={40}></textarea> <button type="submit">Send</button> </form> </main> ) }
Server functions run only on the server, so you cannot use browser APIs inside them.
Use redirect() from next/navigation to send users to another page after form submission.
Always add method="post" to your form to send data securely.
Form actions let you handle form data on the server in Next.js App Router.
Use action functions to process form data and respond or redirect.
This approach keeps your app secure and simple by avoiding client-side form logic.