DEV Community

Nafiz Mahmud
Nafiz Mahmud

Posted on

Next.js Server Actions

Next.js Server Actions is a powerful feature introduced in Next.js that allow you to run server-side code without having to create a separate API endpoint. Server Actions are defined as asynchronous functions marked with the 'use server' directive, and can be called directly from client-side components.

Here's an example of defining a Server Action to add a new todo item to a database:

// app/actions.js
'use server'

import { addTodo } from '@/lib/db'

export async function addTodoAction(formData) {
  const text = formData.get("text")
  await addTodo({ text, completed: false })
}
Enter fullscreen mode Exit fullscreen mode

In a client-side component, you can then call this Server Action using the action prop on a form element:

// app/page.js

import { addTodoAction } from './actions'

export default function TodoPage() {
  return (
    <form action={addTodoAction}>
      <input type="text" name="text" />
      <button type="submit">Add Todo</button>
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

When the form is submitted, Next.js will automatically serialize the form data, send it to the server, execute the addTodoAction function, and return the result back to the client.

Server Actions provide several benefits over traditional API endpoints, including:

No boilerplate: You don't need to create a separate API route, just define the action function.

Type safety: You can use TypeScript to define the input and output of the action, and Next.js will validate it for you.

Seamless client-server communication: The serialization and deserialization of data happens automatically, making it easy to pass data between the client and server.

Overall, Next.js Server Actions are a powerful tool that can
help you write more efficient and maintainable code by
reducing boilerplate and improving the developer experience.

Top comments (0)