Server Actions
Fetching data retrieves information safely (GET requests). When you need to mutate information (like submitting a signup form or deleting a database record), Next.js handles this securely via Server Actions.
Server Actions drastically simplify forms by eliminating the need to construct a separate Express or API endpoint router manually.
Defining a Server Action
A Server Action is an asynchronous function marked with the "use server" directive at the top. This functionally guarantees it strictly executes on the backend without exposing operational logic to the browser package.
// app/actions.ts
"use server"
import { db } from '@/lib/db';
import { revalidatePath } from 'next/cache';
export async function createPost(formData: FormData) {
// 1. Extract values safely from the HTML Form
const title = formData.get('title') as string;
// 2. Execute secure database logic
await db.post.create({ data: { title } });
// 3. Force the cached page to refresh cleanly
revalidatePath('/posts');
}
Using Actions in Components
You can attach Server Actions directly onto standard HTML forms utilizing the action attribute. This operates cleanly seamlessly without needing React.useContext or manual fetch(POST) configurations.
// app/posts/page.tsx
import { createPost } from '../actions';
export default function NewPostForm() {
return (
<form action={createPost}>
<input type="text" name="title" placeholder="Post Title" required />
<button type="submit">Submit Event</button>
</form>
);
}
If the user's browser has JavaScript fully disabled, Server Actions inherently gracefully degrade and continue functioning exactly like standard HTML form submissions from the 1990s!