Server Actions (Forms)
Native HTML form submissions with Progressive Enhancement.
The End of the API Route
Server Actions allow you to run asynchronous code directly on the server without manually writing API endpoints.
In Next.js, Server Actions are deeply integrated into the native HTML <form> element. By passing a Server Action to the action attribute, Next.js wires up the client-to-server communication automatically.
Progressive Enhancement
Because Server Actions use the native action attribute instead of React's onSubmit event handler, they support Progressive Enhancement.
This means your form will successfully submit data to your database even if the user's browser hasn't finished downloading the JavaScript bundle, or if JavaScript is completely disabled.
The 'use server' Directive
To create a Server Action, you simply define an async function and place the 'use server' directive at the top of its body.
Then, pass that function to the form: <form action={createPost}>. Next.js extracts the form fields into a standard Web FormData object, which your action receives as its first argument.
The JS Toggle
Experience Progressive Enhancement in action. Submit the form with JavaScript enabled to see Next.js perform a seamless background fetch. Then, toggle JavaScript OFF and submit again. Notice how it falls back to a native browser POST request with a full page navigation, yet still succeeds!
Client Browser (React)
Create Post
Next.js Server
// Extract data from native FormData
const title = formData.get('title');
// Save to DB...
await db.post.create(title);
Network Request
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Server Actions eliminate the need to write manual API routes for mutations.
- Place the
'use server'directive inside async functions to mark them as Server Actions. - Using
<form action={myAction}>enables Progressive Enhancement. - If JavaScript fails to load, Next.js falls back to a native HTTP POST request.
- Server Actions receive a
FormDataobject containing the input values.
Done with this concept?
Mark it complete to track your progress. No login needed.