Next.js 13/14: Server Actions and the New App Router
In 2023, the React world is in a bit of a transition. The introduction of the App Router in Next.js 13.4 and the subsequent stability of Server Actions in Next.js 14 are changing how we think about full-stack development. We're moving away from the "client-side everything" model and back to something that looks surprisingly like traditional server-side frameworks-but with all the power of React.
Server Actions: Form Handling Made Easy
Before Server Actions, you had to write an API route, use fetch on the client, and handle all the loading and error states manually. Now, you can just define a function that runs on the server and call it directly from your component.
Example: A Modern Comment Form
// app/posts/[slug]/page.tsx
import { db } from '@/lib/db';
export default async function PostPage({ params }: { params: { slug: string } }) {
async function addComment(formData: FormData) {
'use server'; // This is the magic marker!
const content = formData.get('content') as string;
await db.comment.create({
data: { content, postSlug: params.slug }
});
// We can revalidate our data right here
revalidatePath(`/posts/${params.slug}`);
}
return (
<div>
<form action={addComment}>
<textarea name="content" required />
<button type="submit">Add Comment</button>
</form>
{/* List existing comments... */}
</div>
);
}
Server Components vs. Client Components
The biggest mental shift is "Server Components by Default." In the App Router, every component in the app directory is a Server Component unless you add the 'use client' directive. This means:
- No hydration cost: Less JavaScript is sent to the browser.
- Direct database access: You can use
async/awaitand query your DB directly inside your component. - Better SEO: The content is fully rendered on the server.
Revalidation and the Data Cache
In 2023, Next.js has introduced a sophisticated caching layer. You can use fetch with tags:
const res = await fetch('https://api.example.com/data', {
next: { tags: ['my-data'] },
});
And then revalidate those tags from your Server Action:
'use server';
import { revalidateTag } from 'next/cache';
async function updateData() {
// Update DB...
revalidateTag('my-data');
}
In 2023, Next.js is making it easier than ever to build powerful, full-stack applications without the boilerplate of traditional SPAs.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development