"use server" in Next.js

"use server" tells Next.js that a function should run only on the server, not in the browser. It enables secure server actions like database writes or API calls.

What is "use server"?

It marks a function as a server action so sensitive logic runs safely on the backend.

How does it work?

async function action(formData) {
  "use server";
  // server-only logic
}

The function executes on the server even when triggered from the UI.

Why use it?

Example — Server Form Action

The form submits directly to a server action without exposing logic to the browser.

Real-World Example

Submitting an order saves data securely on the server without exposing database credentials to the client.

Interview Tip

"use server" marks a function to execute only on the server, enabling secure server-side actions triggered from UI interactions.