Learn Next.js · 6/15

Server Actions: Mutating Data the Modern Way

8 min read

Server Actions: Mutating Data the Modern Way ⚙️

Welcome back! Today, we're diving into one of the most powerful features in modern Next.js: Server Actions. If you've ever felt the pain of setting up API routes just to handle a simple form submission, you're in for a treat. Server Actions streamline this entire process, making your code cleaner, more secure, and easier to manage.

Let's get started!


1. Introduction to Server Actions: Forms Without APIs 📝

The Problem:

Traditionally, if you wanted to submit a form in a web application, you'd need to:

  1. Create a form in your frontend.
  2. Write a function to handle the form submission, often using useState to manage the form's state.
  3. Create an API endpoint (e.g., /api/submit-form) on your server.
  4. Use fetch or a library like axios to send the form data to that API endpoint.
  5. Handle loading states, errors, and UI updates on the client side.

This approach, while functional, involves a lot of boilerplate code and context switching between your frontend and backend logic. It can feel like you're building a complex bridge just to send a simple message across a small stream.

The Solution: Server Actions

Server Actions are asynchronous functions that run on the server but can be called directly from your React components. They allow you to handle form submissions and data mutations without the need to manually create API endpoints. Next.js automatically handles the underlying POST request and data serialization for you.

Think of it like having a direct, secure line of communication from your component to your server-side logic.

How it Works Under the Hood:

When you use a Server Action with a <form>, Next.js creates a dedicated POST endpoint behind the scenes. When the form is submitted, the browser sends a request to this endpoint, and Next.js executes your server-side function. This approach also benefits from progressive enhancement; if JavaScript is disabled, the form will still work as a standard HTML form submission.

A Simple Example:

Let's create a basic form to add a new item to a list.

First, create a file for your server-side logic, for example, app/actions.ts:

typescript
// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';

export async function createItem(formData: FormData) {
  const rawFormData = {
    itemName: formData.get('itemName') as string,
  };

  // Here you would typically interact with your database
  console.log('New item:', rawFormData.itemName);

  // After mutation, revalidate the path to update the UI
  revalidatePath('/');
}

Now, in your page component, you can use this action directly in your form:

tsx
// app/page.tsx
import { createItem } from './actions';

// This is a placeholder for where you might get your data
const items = ['First Item']; 

export default function HomePage() {
  return (
    <main>
      <h1>My Items</h1>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <form action={createItem}>
        <input type="text" name="itemName" placeholder="Enter new item" required />
        <button type="submit">Add Item</button>
      </form>
    </main>
  );
}

And that's it! No API routes, no fetch calls. Just a form and a server-side function.


2. Executing Server Actions inside Server Components 🖥️

You can define and use Server Actions directly within Server Components. This is great for colocation of logic, keeping your data mutation code right next to the component that uses it.

The Problem:

Sometimes, you have a simple action that is only used by a single Server Component. Creating a separate file for this action might feel like unnecessary fragmentation of your codebase.

The Solution: Inline Server Actions

You can define an async function with the "use server" directive directly inside the function body. This marks the function as a Server Action that will only execute on the server.

Example:

Let's modify our previous example to have the createItem action defined directly within our HomePage component.

tsx
// app/page.tsx
import { revalidatePath } from 'next/cache';

const items = ['First Item'];

export default function HomePage() {
  async function createItem(formData: FormData) {
    'use server';

    const rawFormData = {
      itemName: formData.get('itemName') as string,
    };

    console.log('New item from inline action:', rawFormData.itemName);

    revalidatePath('/');
  }

  return (
    <main>
      <h1>My Items</h1>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <form action={createItem}>
        <input type="text" name="itemName" placeholder="Enter new item" required />
        <button type="submit">Add Item</button>
      </form>
    </main>
  );
}

Key Considerations:

  • Security: Server Actions are designed to be secure. Any data passed to them is part of the request payload, and the server-side code is never exposed to the client.
  • Reusability: If you plan to use the same action in multiple components (including Client Components), it's best to define it in a separate file.

3. Enhancing Client Components: useFormStatus and useFormState 💅

While Server Actions work seamlessly with Server Components, you'll often need to provide a richer user experience with loading states and form validation feedback, which requires Client Components. This is where the useFormStatus and useFormState hooks come into play.

useFormStatus: Providing Pending UI

The Problem:

When a user submits a form, the network request might take a moment. Without any visual feedback, the user might think the form is broken and click the submit button multiple times.

The Solution: useFormStatus

The useFormStatus hook provides the status of the last form submission. It gives you access to a pending property, which is true while the form is being submitted.

Important Note: useFormStatus must be used in a component that is a child of the <form> element.

Example:

Let's create a SubmitButton component that shows a loading state.

tsx
// app/components/SubmitButton.tsx
'use client';

import { useFormStatus } from 'react-dom';

export function SubmitButton() {
  const { pending } = useFormStatus();

  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Adding Item...' : 'Add Item'}
    </button>
  );
}

Now, we can use this SubmitButton in our form:

tsx
// app/page.tsx
import { createItem } from './actions';
import { SubmitButton } from './components/SubmitButton';

const items = ['First Item'];

export default function HomePage() {
  return (
    <main>
      {/* ... list of items ... */}
      <form action={createItem}>
        <input type="text" name="itemName" placeholder="Enter new item" required />
        <SubmitButton />
      </form>
    </main>
  );
}

Now, when the form is submitted, the button will be disabled and show a "Adding Item..." message.

useFormState: Handling Form State and Errors

The Problem:

What if the user submits invalid data? You need a way to receive feedback from the server (e.g., error messages) and display it in the form.

The Solution: useFormState

The useFormState hook allows you to manage the state of a form, including handling responses and errors from a Server Action. It takes the server action and an initial state as arguments and returns the current form state and a new action to pass to the form.

Example:

First, let's update our Server Action to return a message.

typescript
// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';

export async function createItem(prevState: any, formData: FormData) {
  const itemName = formData.get('itemName') as string;

  if (itemName.trim().length < 3) {
    return { message: 'Item name must be at least 3 characters long.' };
  }

  console.log('New item:', itemName);
  revalidatePath('/');
  return { message: 'Item added successfully!' };
}

Now, let's create a Client Component for our form that uses useFormState.

tsx
// app/components/ItemForm.tsx
'use client';

import { useFormState } from 'react-dom';
import { createItem } from '../actions';
import { SubmitButton } from './SubmitButton';

const initialState = {
  message: '',
};

export function ItemForm() {
  const [state, formAction] = useFormState(createItem, initialState);

  return (
    <form action={formAction}>
      <input type="text" name="itemName" placeholder="Enter new item" required />
      <SubmitButton />
      {state?.message && <p>{state.message}</p>}
    </form>
  );
}

Finally, use this ItemForm in your page:

tsx
// app/page.tsx
import { ItemForm } from './components/ItemForm';

const items = ['First Item'];

export default function HomePage() {
  return (
    <main>
      {/* ... list of items ... */}
      <ItemForm />
    </main>
  );
}

With this setup, if the user tries to submit an item with a name shorter than three characters, the error message from the server will be displayed below the form.


4. Updating the UI Automatically: revalidatePath 🔄

The Problem:

After successfully adding, updating, or deleting data, the UI needs to reflect these changes. For example, if you add a new item to a list, it should appear on the page without requiring a manual refresh.

The Solution: revalidatePath

revalidatePath is a function from next/cache that allows you to purge the cached data for a specific path on demand. When you call revalidatePath within a Server Action, Next.js will re-render the specified page on the next visit, ensuring the displayed data is fresh.

How It Works:

Next.js aggressively caches data to improve performance. When you mutate data (e.g., add a record to a database), this cache becomes stale. revalidatePath tells Next.js to invalidate the cache for a given route, so the next time a user visits that page, they get the updated content.

Example:

We've already been using it in our createItem action:

typescript
// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';

export async function createItem(prevState: any, formData: FormData) {
  // ... validation and database logic ...

  // This line is the key!
  revalidatePath('/');

  return { message: 'Item added successfully!' };
}

In this case, after a new item is created, we call revalidatePath('/'). This ensures that the next time the home page (/) is rendered, it will fetch the latest list of items, including the one that was just added.


Conclusion 🎉

Server Actions in Next.js offer a more streamlined and secure way to handle data mutations. By eliminating the need for manual API endpoint creation, they simplify your codebase and improve the developer experience. When combined with hooks like useFormStatus and useFormState, and the revalidatePath function, you have a powerful toolkit for building modern, interactive, and efficient web applications.

Extra Reading 📚

Challenge

Task: Build an Interactive To-Do List with Server Actions

You will create a to-do list application that uses a Next.js Server Action to add new tasks. The form must provide user feedback for submission status and validation errors.

Requirements:

  1. Create the Server Action (createTask):

    • This function must be defined as a Server Action.
    • It should accept the previous state and FormData as arguments.
    • Implement server-side validation: if the submitted task text is fewer than 4 characters, it must return an object with a message property containing an error string. For example: { message: 'Task is too short.' }.
    • If validation passes, simulate adding the new task to a data store.
    • After a successful addition, it must call revalidatePath for the home route ('/') to ensure the UI updates with the new task.
  2. Implement the Client Component (TodoForm):

    • Use the useFormState hook to connect the createTask server action to your form.
    • The form should have a single text input for the new task and a submit button.
    • Conditionally render the validation error message from the form state below the input field.
  3. Create a SubmitButton Component:

    • This component will render the <button type="submit">.
    • Use the useFormStatus hook to get the form's pending state.
    • When the form is pending, the button's text must change from "Add Task" to "Adding..." and it should be disabled to prevent multiple submissions.
  4. Integration:

    • The TodoForm component must use your SubmitButton component.
    • The main HomePage component should display the current list of tasks and include the TodoForm.

Expected result

The final code should correctly implement a server action named createTask in app/actions.js which validates form data. If the input is less than 4 characters, it should return an error object. Otherwise, it should add the task and call revalidatePath('/').

The app/TodoForm.js file should utilize the useFormState hook with createTask and initialState. The returned state should be used to display an error message below the form input. The form's action attribute should be bound to the dispatcher returned by useFormState.

Inside TodoForm.js, a SubmitButton component must use the useFormStatus hook. The hook's pending property should be used to conditionally disable the button and change its text to "Adding..." during form submission.

jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.