Next.js
/Intermediate
Introduction to Server Actions
Definition
Asynchronous JavaScript functions that execute securely on the server, designed to handle form submissions and data mutations without writing separate API endpoints.
Explain Like I'm New
Historically, to save a user's name to a database, you had to build a frontend React form, build a backend `/api/save-name` endpoint, use `fetch()` to connect them, and manage loading states. Server Actions let you write the database code directly inside the React component and attach it straight to the `<form action={saveName}>`. No API routes needed.
Real World Example
Creating a 'Like' button. Clicking it fires a Server Action that directly executes an SQL `UPDATE` query on your server.
Common Use Cases
- •Form submissions
- •Database mutations
- •Rapid full-stack development
Interactive Example
/* Server Actions inside a Server Component */ import db from '@/lib/db'; export default function ServerForm() { // 1. Define the action // It MUST be async, and it MUST have 'use server' async function createPost(formData: FormData) { 'use server'; // 2. This code runs securely on the Node.js server! const title = formData.get('title'); await db.post.create({ data: { title } }); } return ( // 3. Attach it directly to the native HTML action attribute! <form action={createPost}> <input name="title" type="text" /> <button type="submit">Publish</button> </form> ); }
Interview Questions
basic
- What directive must be placed at the top of a function to turn it into a Server Action?
intermediate
- Can you call a Server Action from a Client Component (a file with `'use client'`)?