Server Actions
Server Actions
Next.js's server function call feature. Simplifies form submission and data mutation.
Server Actions
Next.js's server function call feature. Simplifies form submission and data mutation.
Server Actions is a feature introduced in Next.js 13.4 that lets you call server functions directly from client components. It uses the 'use server' directive to mark a function so that it runs only on the server, and it allows data mutations without creating an API route.
The biggest advantage of Server Actions is the simplification of form handling. When you pass a server function directly to the action attribute of a form, it automatically supports Progressive Enhancement, which works even in environments where JavaScript is disabled.
Server Actions naturally integrate the RPC (Remote Procedure Call) pattern into React. Because server code is not included in the client bundle, security is strengthened, and database queries or external API calls can be defined in the same file as the component.
When used together with revalidatePath or revalidateTag, the cache can be automatically refreshed after a mutation. Combined with the useFormStatus and useFormState hooks, loading state display and optimistic updates can also be implemented.
// app/actions.ts - Server Actions μ μ
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod';
import { db } from '@/lib/db';
// μ€ν€λ§ κ²μ¦
const PostSchema = z.object({
title: z.string().min(1, 'μ λͺ©μ μ
λ ₯νμΈμ'),
content: z.string().min(10, 'λ΄μ©μ 10μ μ΄μμ΄μ΄μΌ ν©λλ€'),
});
// νΌ μν νμ
type FormState = {
errors?: { title?: string[]; content?: string[] };
message?: string;
};
// κ²μκΈ μμ± Action
export async function createPost(
prevState: FormState,
formData: FormData
): Promise<FormState> {
// μ ν¨μ± κ²μ¬
const validatedFields = PostSchema.safeParse({
title: formData.get('title'),
content: formData.get('content'),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: 'μ
λ ₯κ°μ νμΈν΄μ£ΌμΈμ.',
};
}
try {
await db.post.create({
data: validatedFields.data,
});
} catch (error) {
return { message: 'κ²μκΈ μμ±μ μ€ν¨νμ΅λλ€.' };
}
revalidatePath('/posts');
redirect('/posts');
}
// μμ Action
export async function deletePost(id: string) {
await db.post.delete({ where: { id } });
revalidatePath('/posts');
}
// app/posts/new/page.tsx - νΌ μ»΄ν¬λνΈ
'use client';
import { useFormState, useFormStatus } from 'react-dom';
import { createPost } from '../actions';
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'μ μ₯ μ€...' : 'κ²μνκΈ°'}
</button>
);
}
export default function NewPostForm() {
const [state, formAction] = useFormState(createPost, {});
return (
<form action={formAction}>
<input name="title" placeholder="μ λͺ©" />
{state.errors?.title && <p>{state.errors.title[0]}</p>}
<textarea name="content" placeholder="λ΄μ©" />
{state.errors?.content && <p>{state.errors.content[0]}</p>}
<SubmitButton />
{state.message && <p>{state.message}</p>}
</form>
);
}
In a technical meeting:
"You don't need to create a separate API route for form submission. With Server Actions, you can define a server function right in the component file. Types are shared automatically too."
In a technical interview:
"What are the security advantages of Server Actions?" - "'use server' functions are not included in the client bundle. They run only on the server, so DB connection information and API keys are not exposed."
In a code review:
"If you throw an error in a Server Action, the error message is exposed to the client as is. Switch to a pattern that returns an error object, and only log sensitive information."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free