What a Server action actually is
A Server Action is a function marked with use server that you can call from a Client Component as if it were local. Behind the scenes, Next.js turns the call into an HTTP request. You get the ergonomics of a function call and the guarantees of server-side code.
'use client';
import { createBook } from '../actions';
import { useState } from 'react';
export function NewBookForm() {
const [pending, setPending] = useState(false);
async function handleSubmit(formData: FormData) {
setPending(true);
await createBook(
formData.get('title') as string,
formData.get('author') as string,
);
setPending(false);
}
return (
<form action={handleSubmit}>
<input name="title" placeholder="Title" />
<input name="author" placeholder="Author" />
<button disabled={pending}>Save</button>
</form>
);
}The client imports the action and calls it like a regular async function.
Read the form element. Its action prop takes the server function directly. When the form submits, Next.js serializes the FormData, sends it to the server, runs the action, and returns the result. You wrote what looks like a plain function call and got a fully working mutation endpoint.
How a Server Action travels
The client sees a function call. Next.js turns it into an HTTP request and runs the real code on the server.
Quiz: Quiz
Loading practiceโฆ