Part 102: Revolutionizing Form Submission with Server Actions in Next.js
[App] Server Actions

With the release of Next.js version 14, a new and exciting feature called Server Actions has been introduced, transforming how we handle form submissions. By moving the form processing logic to the server, Server Actions streamline the development process, making it more efficient and less complex. In this blog post, we'll explore how Server Actions work and how they simplify form handling compared to traditional methods.
Understanding Server Actions
Server Actions allow us to define server-side logic directly within components, eliminating the need for separate API routes for form submissions. This feature is particularly beneficial in scenarios where we need to interact with a database or perform secure operations that should not be exposed to the client side.
Implementing a Server Action
To illustrate the power of Server Actions, let's walk through a practical example of implementing a comment submission form using this new feature.
Step 1: Define the Server Action
In a Next.js application, you can define a Server Action within a Server Component. The Server Action is essentially a function that runs on the server. Here's how you can set it up:
// app/reviews/[slug]/page.jsx
export default async function ReviewPage({ params: { slug } }) {
return (
<>
<section>
<h2>Comments</h2>
<CommentList slug={slug} />
</section>
</>
);
}// components/CommentForm.jsx
import { createComment } from '@/lib/comments';
export default function CommentForm({ slug, title }) {
async function action(formData) {
'use server';
const comment = await createComment({
slug,
user: formData.get('user'),
message: formData.get('message'),
});
console.log('created:', comment);
}
return (
<form action={action}
className="border bg-white flex flex-col gap-2 mt-3 px-3 py-3 rounded">
<p className="pb-1">
Already played <strong>{title}</strong>? Have your say!
</p>
<div className="flex">
<label htmlFor="userField" className="shrink-0 w-32">
Your name
</label>
<input id="userField" name="user"
className="border px-2 py-1 rounded w-48"
/>
</div>
<div className="flex">
<label htmlFor="messageField" className="shrink-0 w-32">
Your comment
</label>
<textarea id="messageField" name="message"
className="border px-2 py-1 rounded w-full"
/>
</div>
<button type="submit"
className="bg-orange-800 rounded px-2 py-1 self-center
text-slate-50 w-32 hover:bg-orange-700">
Submit
</button>
</form>
);
}Step 2: Handling Form Data with FormData
When the form is submitted, the action function is triggered on the server. The form data is automatically passed to this function as a FormData object, allowing us to access the input values using the get method. This simplifies the process of extracting form data for server-side operations.
Step 3: Saving Data to the Database
With the createComment function, we can save the form data to the database. By importing this function and calling it within the Server Action, we keep the database logic neatly encapsulated within the component.
Step 4: Testing the Implementation
Once the Server Action is set up, we can test the form submission. Upon submitting the form, the console will log the newly created comment, confirming that the data has been successfully saved to the database.
Benefits of Using Server Actions
Reduced Complexity: Server Actions eliminate the need for separate API routes, reducing the complexity of handling form submissions.
Improved Security: By running logic on the server, sensitive operations remain secure and out of reach from the client side.
Streamlined Codebase: Keeping form processing logic within the same component enhances maintainability and readability.
Conclusion
Server Actions in Next.js offer a revolutionary approach to handling form submissions, making the process more efficient and secure. By moving logic to the server, developers can enjoy a more streamlined workflow and a cleaner codebase. As you adopt this feature in your projects, you'll likely find it a valuable tool for building robust and maintainable web applications.
Last updated