Part 103: Enhancing User Experience with Automatic Page Updates in Next.js
[App] Server Actions

In modern web applications, providing a seamless user experience is crucial. One common requirement is ensuring that users can see updates in real-time without the need for manual page refreshes. With the advent of Server Actions in Next.js, this has become easier to implement. In this blog post, we'll explore how to update a comment list automatically after a form submission, without requiring a page reload.
The Challenge: Seeing Real-Time Updates
Previously, we implemented a Server Action to handle comment submissions in a Next.js application. While the comment was successfully added to the database, the page did not automatically display the new comment. Users were required to refresh the page manually to see updates, which is not an ideal user experience.
How Server Actions Work
Before addressing the automatic update issue, let's delve into how Server Actions operate in terms of network requests. When a form is submitted, Next.js sends a POST request to the same URL as the page, but with some additional data to identify the specific Server Action being called. This is performed using the fetch API, which is part of Next.js's internal mechanism.
The request headers include a Content-Type of multipart/form-data, which is standard for form submissions. The payload contains the form data along with some extra fields added by Next.js to manage the Server Action.
Implementing Automatic Updates
To ensure that the comment list updates automatically after a submission, we need to incorporate a redirection mechanism. This approach uses a simple yet effective strategy: redirecting to the same page after the form submission, which triggers a re-render with the updated data.
Step-by-Step Implementation
Step 1: Sorting Comments
Firstly, we want to display the comments in descending order based on the postedAt timestamp, ensuring the most recent comments appear first. This can be achieved by modifying the database query:
// lib/comments.js
export async function getComments(slug) {
return await db.comment.findMany({
where: { slug },
});
}Step 2: Adding Redirection in Server Action
Next, we modify our Server Action to include a redirection after successfully creating a comment. This redirection signals Next.js to refresh the component with the latest data.
// components/CommentForm.jsx
import { redirect } from 'next/navigation';
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);
redirect(`/reviews/${slug}`);
}
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 3: Testing the Implementation
With these changes, submitting a comment will trigger a POST request and subsequently redirect to the same page. This results in an updated view where the newly added comment appears instantly.
How It Works
The redirection leverages the Next.js client-side router to refresh the page. The response from the server includes an X-Action-Redirect header, indicating the target URL. As a result, the page reloads with the latest data, eliminating the need for manual refreshes.
Conclusion
By utilizing Server Actions and redirection, we have enhanced the user experience in our Next.js application, allowing for real-time updates of the comment list. This approach not only simplifies the process but also maintains a clean and responsive user interface. As we continue to explore the capabilities of Next.js, features like Server Actions will undoubtedly prove invaluable in building dynamic and interactive web applications.
Last updated