Server Actions & Form Submissions
Server Actions are asynchronous functions that run on the server. They integrate directly with forms, allowing you to handle form submissions and database mutations without writing manual API routes.
1 use server, progressive enhancement and client states
Server Actions provide a seamless way to handle form submissions:
- "use server" directive: Declares a function as a Server Action that runs exclusively on the server.
- Progressive Enhancement: Forms can be submitted even if client-side JavaScript is not fully loaded or is disabled in the browser.
- Form Validation & Revalidation: Revalidate cached data dynamically using
revalidatePath()after database mutations.
2 Writing a Form Server Action
Let's check how to define a Server Action and bind it to a form:
React — Server Action
// Import revalidation utility
import { revalidatePath } from 'next/cache';
export default function NewTaskForm() {
// Define action inside component or separate action file
async function addTask(formData) {
"use server"; // marks function as running on the server
const taskTitle = formData.get('title');
console.log('Saving task to database:', taskTitle);
// Revalidate index page cache dynamically
revalidatePath('/');
}
return (
<form action={addTask}>
<input name="title" placeholder="New Task Title" required>
<button type="submit">Add Task</button>
</form>
);
}
3 Code Challenge
Challenge: Write a form that captures a user email. Bind it to a Server Action, print the email value in the server terminal, and display a success status message in the browser.