Server Actions (Forms)

Native HTML form submissions with Progressive Enhancement.

Next.js7 min readConcept 31 of 65

The End of the API Route

Server Actions allow you to run asynchronous code directly on the server without manually writing API endpoints.

In Next.js, Server Actions are deeply integrated into the native HTML <form> element. By passing a Server Action to the action attribute, Next.js wires up the client-to-server communication automatically.

Progressive Enhancement

Because Server Actions use the native action attribute instead of React's onSubmit event handler, they support Progressive Enhancement.

This means your form will successfully submit data to your database even if the user's browser hasn't finished downloading the JavaScript bundle, or if JavaScript is completely disabled.

The 'use server' Directive

To create a Server Action, you simply define an async function and place the 'use server' directive at the top of its body.

Then, pass that function to the form: <form action={createPost}>. Next.js extracts the form fields into a standard Web FormData object, which your action receives as its first argument.

The JS Toggle

Experience Progressive Enhancement in action. Submit the form with JavaScript enabled to see Next.js perform a seamless background fetch. Then, toggle JavaScript OFF and submit again. Notice how it falls back to a native browser POST request with a full page navigation, yet still succeeds!

NATIVE RELOAD

Client Browser (React)

Create Post

Next.js Server

actions.ts
export async function createPost(formData: FormData) {
'use server';

// Extract data from native FormData
const title = formData.get('title');

// Save to DB...
await db.post.create(title);
}

Network Request

Waiting for submission...

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary benefit of using `<form action={myAction}>` instead of `<form onSubmit={myHandler}>`?
  2. 2When a Server Action is triggered by a form `action`, what is passed as the first argument to the action function?

Remember this

  • Server Actions eliminate the need to write manual API routes for mutations.
  • Place the 'use server' directive inside async functions to mark them as Server Actions.
  • Using <form action={myAction}> enables Progressive Enhancement.
  • If JavaScript fails to load, Next.js falls back to a native HTTP POST request.
  • Server Actions receive a FormData object containing the input values.

Done with this concept?

Mark it complete to track your progress. No login needed.