# Server actions

> Calling the server from a client component, as an ordinary function.

A server action is an async function that a client component calls like any
other function. It runs on the server. Mark its module `"use server"`, and
every export can be called from the browser.

## Writing one

```ts title="src/actions.ts"
'use server'

import { revalidate } from '@rsc-kit/core/revalidate'
import { addOrder } from './orders'

let total = 0

// Called straight from a client component as an ordinary async function. The
// body never reaches the browser; the call becomes a POST to /_rsc/action.
export async function addToTotal(amount: number): Promise<number> {
  total += amount

  return total
}

// Marks the orders list stale. The re-rendered list travels back with this
// action's own answer, so the client never makes a second request for it.
export async function placeOrder(item: string): Promise<{ ok: true }> {
  await addOrder(item)
  revalidate('orders')

  return { ok: true }
}
```

Nothing is registered and nothing is generated. The build turns each export
into a reference.

## Calling one

Import it into a client component and call it:

```tsx title="src/components/AddOrder.tsx"
'use client'

import { useState } from 'react'
import { placeOrder } from '../actions'

export function AddOrder() {
  const [item, setItem] = useState('')
  const [note, setNote] = useState('')

  return (
    <div className="add-order">
      <input value={item} onChange={(e) => setItem(e.target.value)} placeholder="Item" id="item" />
      <button
        id="place"
        onClick={async () => {
          await placeOrder(item)
          setItem('')
        }}
      >
        Place order
      </button>
      {/* Deliberately untouched by the action: proof the page was not replaced. */}
      <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="A note" id="note" />
    </div>
  )
}
```

The import doesn't bring `actions.ts` into the browser bundle. Whatever that
module imports, such as a database client or a secret, stays on the server.

Arguments and return values can be anything React can serialize, files
included. See [File uploads](/guides/file-uploads).

With a Laravel or Go backend, the backend's actions are generated as one
module per class, and you call them the same way:

```tsx
import * as orders from './server-actions/orders'

await orders.create(form)
```

<Aside type="danger" title="An action is a public endpoint">
  Anything exported from a `"use server"` module can be called by anyone who
  can reach your server, without your page. Check who is calling **inside the
  action**. Hiding the button is not a check. See
  [Authorization](/guides/authorization#protect-a-server-action).
</Aside>

## Refreshing what the action changed

Call `revalidate` with the name of what changed. `placeOrder` above writes the
order and then calls `revalidate('orders')`. The name is a
[section](/guides/sections), a region of the page the server can render on
its own:

```tsx title="src/app/orders/orders.section.tsx"
import { section } from '@rsc-kit/core/section'
import { listOrders } from '../../orders'

// A named region. section() registers it under a name the client can refresh
// and an action can mark, so this list re-renders without the page around it
// being touched.
async function Orders() {
  const orders = await listOrders()

  return (
    <ul className="orders">
      {orders.map((order) => (
        <li key={order.id}>{order.item}</li>
      ))}
    </ul>
  )
}

export default section('orders', Orders)
```

The re-rendered section comes back **with the action's own answer**, in one
request. Nothing else on the page renders again. Type into the second input in
`AddOrder`, place an order, and what you typed is still there.

`revalidate('page')` re-renders the whole page, and `revalidate('all')` the
layouts too. Either way:

- **What is on screen is updated in place.** A form's state, a modal opened
  from `onSuccess` and a toast in the layout all survive. A one-time secret
  shown after the action is still there.
- **The new render sees the write.** A `cache()`d read made before the write is
  forgotten, so a renamed row is renamed in the sidebar too, not only in the
  table.
- **Older prefetches are dropped.** Pages prefetched for other links, and pages
  kept for the back button, are from before the write. Visiting the list after
  creating a row fetches it again, with the row in it. `refresh()` does the
  same.
- **The answer only applies to the page that sent it.** If the visitor
  navigated away while the action ran, the page now on screen was fetched
  before the write, so it is fetched again whole, as `refresh('all')` would. A
  modal opened over the page in the meantime doesn't count as leaving.

`section()` is not a client module: what it wraps is a server component that
fetches its own data.

## Validating input

`createActionClient` builds actions with a schema and middleware, so the
checks, the context and the types come from one declaration:

```ts title="src/lib/action.ts"
import { createActionClient } from '@rsc-kit/core/action';

export const action = createActionClient({
  // A failure's message may name a query, a path or a host.
  // Show something fixed unless you raised the error yourself.
  onError: (error) => (error instanceof AppError ? error.message : 'Something went wrong.'),
});
```

```ts title="src/actions.ts"
'use server'

import { z } from 'zod';
import { action } from './lib/action';

export const createPost = action
  .use(async ({ next }) => next({ ctx: { user: await currentUser() } }))
  .use(async ({ ctx, next }) => {
    if (!ctx.user) throw new AppError('Sign in first');

    return next({ ctx: { audit: `user:${ctx.user.id}` } });
  })
  .input(z.object({ title: z.string().min(3), body: z.string().min(10) }))
  .handler(async ({ input, ctx }) => {
    return savePost({ ...input, authorId: ctx.user.id });
  });
```

- `input` is typed from the schema, and `ctx` from every middleware that ran.
  Add a `.use()` and the handler's `ctx` grows; change the schema and the
  handler stops compiling.
- Middleware runs outermost first and wraps what follows, so a step can time
  or clean up around the rest. Throw to refuse.
- Return what `next()` gave you. A step that neither calls `next()` nor throws
  is reported as a mistake, since a forgotten `next()` would otherwise look
  like a check that passed.

This is a different thing from `middleware.ts`, which decides whether a page
may render. An action can be called without any page, so it defends itself.

### Reading the result

An action built this way never throws. It returns an object:

```ts
const result = await createPost({ title: 'x', body: 'y' });

result.data              // what the handler returned
result.validationErrors  // { title: ['Too short'] }
result.serverError       // 'Something went wrong.' - or a refusal's own message
result.refusal           // what refuse() carried beside it, typed - see below
result.redirected        // '/dashboard' - it redirect()ed
```

- `serverError` is the backend's own message when the backend turned the call
  down rather than failed: a refusal with a status (Go's `Refuse(503, "busy")`,
  Laravel's `abort(429)`), not signed in, not allowed, or nothing there. Only a
  failure is replaced by `onError`'s message.
- A read built with `.query()` rejects with the same message, and a page that
  reads through it answers 401, 403 or its not-found page.
- An action that `redirect()`s resolves with `redirected` set once the
  navigation has started, and every other field is `undefined`.
- The argument is typed by the schema, so `createPost({ title: 1 })` fails the
  typecheck. `FormData` is accepted too, which is how a form calls it.

Failures are returned rather than thrown because React hides a thrown error's
message in production, so the fields it named would be lost.

`<Form>` reads this shape directly:

```tsx
<Form action={createPost} schema={schema}>
```

The schema then runs in the browser, so a mistake costs no round trip, and
again in the action, because the action can be called without the form.

### Calling one from a button

Without a form, use `useAction`. It wraps the call in a transition and keeps
the last result:

```tsx title="src/app/posts/archive-button.tsx"
'use client'
import { useOptimistic } from 'react'
import { useAction } from '@rsc-kit/core/useAction'
import { archivePost } from './actions'

export function Posts({ posts }) {
  const [shown, hide] = useOptimistic(posts, (list, id: number) => list.filter((p) => p.id !== id))
  const { execute, isPending } = useAction(archivePost, {
    optimistic: ({ id }) => hide(id),
    onError: (message) => toast.error(message),
  })

  return shown.map((post) => (
    <button key={post.id} disabled={isPending} onClick={() => execute({ id: post.id })}>
      Archive {post.title}
    </button>
  ))
}
```

- `execute` takes what the action's schema takes. `executeAsync` resolves with
  the result.
- `onSuccess` gets what the handler returned. `onError` gets the
  `serverError`, or the first validation message. `onSettled` runs after
  either.
- A backend's generated stub works the same way:
  `useAction(verification.send)`. `onSuccess` gets what the backend returned,
  and a refusal reaches `onError`.
- `optimistic` runs inside the transition, before the call. A failed action
  undoes it on its own, because the optimistic state ends with the transition.
- Neither call throws. Anything thrown on the way, the network included,
  becomes a `serverError`.
- An action that redirected runs no callback and sets no state.
- `status` is `"idle"`, `"executing"`, `"hasSucceeded"` or `"hasErrored"`,
  `result` is the last answer, and `reset()` forgets it. `execute` keeps one
  identity across renders.

### Failing on something a schema cannot know

```ts
.handler(async ({ input, fieldErrors }) => {
  if (await slugTaken(input.slug)) return fieldErrors({ slug: 'Already taken' });

  return save(input);
})
```

The message arrives in `validationErrors` on the field you named, like a schema
failure, so a form shows it in the same place. The field names are typed from
the schema: `fieldErrors({ slgu: … })` doesn't compile.

Write `return fieldErrors(…)`. It throws either way, but without the `return`
TypeScript can't tell that the branch is over, and a value you checked is still
`possibly undefined` on the next line.

A string is one message and an array is several. The empty key is for a
message about no field in particular:

```ts
return fieldErrors({ '': 'Sign-ups are closed for the weekend' });
```

:::note[Porting from next-safe-action]
`return returnValidationErrors(schema, { email: { _errors: ['Account not found'] } })`
becomes `return fieldErrors({ email: 'Account not found' })`.
:::

### Refusing, with something to act on

Sometimes the input is fine and the answer is still no: a project that can't be
deleted while orders are attached to it. The page usually needs more than a
sentence, such as links to those orders. Declare what a refusal carries with
`.refusal()`:

```ts
const blockers = z.object({
  blockers: z.array(z.object({ id: z.number(), href: z.string() })),
});

export const deleteProject = action
  .input(z.object({ id: z.number() }))
  .refusal(blockers)
  .handler(async ({ input, refuse }) => {
    const attached = await ordersFor(input.id);

    if (attached.length) {
      return refuse('Still in use', {
        blockers: attached.map((o) => ({ id: o.id, href: `/orders/${o.id}` })),
      });
    }

    await removeProject(input.id);
  });
```

```ts
const result = await deleteProject({ id });

result.serverError       // 'Still in use'
result.refusal?.blockers // [{ id: 7, href: '/orders/7' }], typed from the schema
```

In a form, `formRefusal` carries the data beside `formError`:

```tsx
<Form action={deleteProject}>
  {({ formError, formRefusal }) => (
    <>
      {formError && <p role="alert">{formError}</p>}
      {formRefusal?.blockers.map((b) => (
        <Link key={b.id} href={b.href}>Order {b.id}</Link>
      ))}
    </>
  )}
</Form>
```

- **The message is always sent.** `onError` never replaces it.
- **The data is checked** against the schema given to `.refusal()`. Data that
  doesn't match is answered as a server bug. An action that declares no schema
  sends no data, and the server's log says so.
- **Refuse from anywhere.** The handler's `refuse` is typed to the schema. The
  `refuse` exported from `@rsc-kit/core/action` takes anything, for a
  middleware or a helper. A backend refuses the same way, with Laravel's
  `Rsc::refuse()` or Go's `RefuseWith`, and its refusal arrives as the same
  `result.refusal`.
- **Elsewhere:** `formRefusal` is typed from the form's `action`. A component
  further down reads it with `useForm<Values, Refusal>()`, and `useAction`
  returns the whole result, `refusal` included.

### Plain functions and generated actions

A plain `"use server"` function, or a backend's generated action, has no result
object. **Anything that didn't happen rejects, and only a redirect resolves:**

- A refusal rejects with an `ActionRefusedError` carrying the message and the
  backend's `status`. A backend that turns the caller away answers 401 (not
  signed in), 403 (not allowed) or 404 (nothing there: Go's
  `Refuse(404, ...)`, Laravel's `abort(404)`, or the action's own
  `notFound()`). An action has no not-found
  page, so a 404 is the message, never a 500.
- Input the backend refused, with `fieldErrors()` or a `ValidationException`,
  rejects with a `ServerValidationError` with `.fieldErrors` and `.formErrors`.
  Both errors come from `@rsc-kit/core/errors`.
- Through a generated stub, `<Form action={orders.delete}>` shows either as it
  always does, the refusal as `formError`, and `useAction` reports it as
  `serverError`.

So a success toast or a navigation to an id that never came back doesn't run
for a write that didn't happen, and `isRedirected` is the only check you need
on what resolved. A refusal's data isn't sent, since there is no
`.refusal(schema)` to check it against. To act on it, call the backend with
`rpc()` from an action built with `createActionClient()` that declares one.

## Setting a cookie

```ts
'use server';

import { cookies } from '@rsc-kit/core/request';

export async function login(formData: FormData) {
  const session = await authenticate(formData);

  (await cookies()).set('session', session.token, {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    maxAge: 60 * 60 * 24 * 7,
  });
}
```

The cookie is set on the action's response, so the next navigation carries it.
`delete` expires one, which is what signing out is. `get`, `set` and `delete`
are all an auth library needs, so you can wire in whichever one you use. See
[Writing to the response](/guides/authorization#writing-to-the-response) for
where else it works.

## A message for the next page

When an action redirects, the form that called it is gone. To show "Saved." on
the page it lands on, flash a one-time message:

```ts
'use server';

import { flash } from '@rsc-kit/core/flash';
import { redirect } from '@rsc-kit/core/redirect';

export async function saveProduct(formData: FormData) {
  await products.save(formData);
  await flash('Product saved.');

  redirect('/products');
}
```

Show it with `useFlash`, in a component you render once in the root layout:

```tsx title="src/app/toasts.tsx"
'use client';

import { useFlash } from '@rsc-kit/core/useFlash';
import { toast } from 'sonner';

export function Toasts() {
  useFlash(({ message, kind }) => (kind === 'error' ? toast.error : toast.success)(message));

  return null;
}
```

- `kind` is `'success'` (the default), `'error'`, `'info'` or `'warning'`. Two
  calls are two messages.
- `flash()` sets a cookie, so call it where a cookie can be set: an action,
  middleware or a `route.ts`, not a page.
- `useFlash` checks when it mounts, after every navigation and, where the
  browser supports CookieStore, whenever a response sets it, so an action that
  stays on the page shows its message too.
- Each message is shown once, then cleared. Unread, it lapses after a minute.
- A page never reads it, so a stored or edge-cached page stays cacheable.

The cookie is readable by script, so put a message in it, never data, and
render it as text.

## Work the visitor should not wait for

`after()` runs work once the answer is on its way, such as an audit row or a
welcome email:

```ts
'use server';

import { after } from '@rsc-kit/core/request';

export async function signup(formData: FormData) {
  const user = await createUser(formData);

  after(() => sendWelcomeEmail(user));
  after(() => audit('signup', user.id));

  redirect('/welcome');
}
```

Don't use a promise you never await instead. On a Worker, the isolate is torn
down when the response ends, and the work dies some of the time. `after()`
hands it to the platform's `waitUntil` where there is one, and the process
keeps it elsewhere. A rejection is logged and never reaches the response.

It works in a component, a `middleware.ts`, an API route and an action.
Outside a request, during a build, the work simply runs.

## Returning UI

An action can return elements instead of data: server components, client
components and Suspense boundaries. The caller gets React elements to render:

```tsx title="src/actions.tsx"
'use server';

import { Suspense } from 'react';
import { Counter } from './Counter';

export async function renderCard(name: string) {
  return (
    <section>
      <h2>{name}</h2>
      <Counter />
      <Suspense fallback={<p>loading…</p>}>
        <Related to={name} />
      </Suspense>
    </section>
  );
}
```

```tsx title="src/CardButton.tsx"
'use client';

const [ui, setUi] = useState<ReactNode>(null);

<button onClick={async () => setUi(await renderCard('ada'))}>card</button>
{ui}
```

The answer streams. The card mounts with its fallback showing, and `<Related>`
fills in when it is done. The browser never receives `<Related>`'s code, only
its output.

### Streaming tokens

An async component that renders one chunk and suspends on the next streams an
answer token by token:

```tsx title="src/actions.tsx"
'use server';

export async function ask(prompt: string) {
  const tokens = model.stream(prompt);   // an AsyncIterator<string>

  return (
    <Suspense fallback={<p>thinking…</p>}>
      <Tokens from={tokens[Symbol.asyncIterator]()} />
    </Suspense>
  );
}

async function Tokens({ from }: { from: AsyncIterator<string> }) {
  const { value, done } = await from.next();

  if (done) return null;

  return (
    <>
      {value}
      <Suspense fallback={null}>
        <Tokens from={from} />
      </Suspense>
    </>
  );
}
```

This is what `createStreamableUI` from Vercel's AI SDK does, in Next as here.
Use it when the server decides what to render: a card, a chart, a widget. For a
chat, stream data instead (`streamText` and `useChat` in the AI SDK): a
half-streamed element tree can't be cancelled, resumed, retried or saved.

## Two actions at once

Two calls fired together run at the same time. Next runs one server action at
a time per client; rsc-kit doesn't queue them. A double-clicked "add to cart"
sends two calls either way, and here they overlap.

So a handler that reads a value, changes it and writes it back can lose an
update. Fix it as you would anywhere:

- do the read and the write in one transaction
- use an atomic update instead of read-modify-write
- accept an idempotency key from the form

Each action gets its own request scope, so two at once never mix their
cookies, headers or revalidations.

When both re-render the same region, the response that arrives last wins.
That is usually the one that committed last, but not always, and nothing
detects it. Sorting them by when they were sent would be worse: a slow first
action can commit after a fast second one. If several actions touch the same
region, let the last answer win or run them one at a time.

`<Form>` gives you `pending` for that, but doesn't guard itself: disable the
button, or a double-click sends two requests.

## Handling errors

| The action | The call |
| --- | --- |
| redirected | **resolves** with `{ redirected }` and starts the navigation. Nothing to catch. |
| answered 422 | throws `ServerValidationError`, with the messages in `errors`. `<Form>` shows them. |
| failed any other way | throws an `Error` naming the status. |

```tsx
"use client";

import { ServerValidationError } from '@rsc-kit/core/errors';
import { createPost } from '../actions';

try {
  await createPost(title, body);
} catch (error) {
  if (error instanceof ServerValidationError) {
    // error.errors — { title: ['Too short'], body: ['Required'] }
  }
}
```

An expired session answers with a redirect, so the visitor lands on the login
page rather than seeing a message about it. [Validation](/guides/validation)
shows the same flow in a form, with no `try`/`catch`.

## How a call travels

1. The client component calls the function.
2. React serializes the arguments.
3. The browser sends one `POST /_rsc/action` with the action's id and the
   arguments.
4. The server decodes them and runs the function.
5. The return value is serialized and streamed back.

A redirect travels as an `X-RSC-Redirect` header. The id is a hash of the
module and the export in a build, such as `9396f92f746f#createOrder`, and
nothing about the file is in it. In development it is the module's path as
Vite serves it (`/@fs/Users/…/actions.ts#createOrder`), which is what a
`$ACTION_ID_…` hidden input in a form shows there.
