Server action is an asynchronous function designed to be executed on the server. They can be called directly inside a component, whether it is client or server component, which makes them the perfect choice for handling form submissions without having to create a separate API endpoint.
Define a server action
Server actions can be defined by creating a actions.js
under the src
directory.
1src
2├── actions.js <===== Server actions
3└── app
4 ├── favicon.ico
5 ├── globals.css
6 ├── layout.jsx
7 └── page.jsx <===== Webpage
app/actions.js
1"use server";
2
3export async function createUser(data) {
4 const name = data.get("name");
5 const email = data.get("email");
6
7 // Simulate saving to a database
8 console.log(name);
9 console.log(email);
10}
There are a few things you must pay attention here, first of all, the actions.js
file must start with a "use server"
directive. This tells Next.js that all the functions defined in this file must be executed on the server, which is the whole purpose of a server action.
Next, as an example, let's create a createUser()
function. When the form is submitted, this function will be executed. The form data will be passed along to createUser()
, allowing the function to process them in the backend.
And because the network calls involved are always asynchronous, all the server action functions must be marked as async
as well.
By default, the function createUser()
accepts a FormData
object input argument. The form data will be passed automatically when the form is submitted, as we are going to see later.