Server Actions are functions that run on the server and are triggered from the client. They enable developers to write server-side logic in a way that feels similar to writing client-side code. This feature allows for server-side data fetching, processing, and mutations without exposing this logic to the client, thus improving security and efficiency.
We can utilize server actions by using the 'use server'
directive. For example, we can create one inside our server component like so:
const NewTodoForm = async () => {
const addTodo = async (formData) => {
'use server';
await db.todo.create({
...
});
};
return (
<form action={addTodo}>
<input name="todo" type="text" />
<button type="submit">Add todo</button>
</form>
)
}
If we perform a mutation in our server action, such as updating records and need that change to be reflected on the UI, we can use revalidatePath
to fetch the data again for that given path:
export const checkTodo = async (id) => {
const todo = await db.todo.findUnique({...});
await db.todo.update({...});
revalidatePath('/todos');
};