NextJS FormData & Server Actions

NextJS FormData & Server Actions

In this example we'll see a new way to access form data in NextJS using server actions to get user submissions or uploading files.

Server Actions is a brand-new feature in Next.js 13. It is constructed over React Actions.

When a user takes an action on the client, the server can execute code using server actions.

For instance, you can run code on the server to process the form data once a user submits it.

Learn how to send form data with Server Actions in this article.

Let's use the following command to create a new Next.js application:

npx create-next-app@latest

Add the following code to the next.config.js file to enable the experimental server actions feature:

const nextConfig = {
  experimental: {
    serverActions: true,
  },
};

Use the code below to create a new page at app/login/page.tsx containing a login form:

export default function LoginPage() {
  return (
    <form method="POST">
      <input type="text" name="name" />
      <input type="email" name="email" />
      <input type="password" name="password" />
      <button type="submit">Login</button>
    </form>
  );
}

You can get to this page by going to /login.

Now that the form submission is being handled, a function may be added to the page component. When the form is submitted by the user, this method will be invoked:

export default function LoginPage() {
  const login = async (formData: FormData) => {
    "use server";

    const name = formData.get("name");
    const email = formData.get("email");
    const password = formData.get("password");

    console.log({ name, email, password });
  };
}

Only the server will be used to perform this function thanks to the "use server" directive.

We may use the FormData API to get the form data within the login() function. The data from the form can then be processed and saved to the database.

Let's add the action attribute to the form element and use this method to handle the form submission:

<form action={login} method="POST">
  <!-- our previous form here -->
</form>

By combining server actions with FormData we have a better way to handle form data in our Next.js application to get user submissions or uploading files.


  • Date: