Guide

Action Client

Compose immutable action builders with generic unexpected-error handling and typed middleware.

Action client

Create a shared client and reuse it across action files. Builder methods create new builders; adding middleware to one branch does not modify the original client.

server/utils/action-client.ts
import { createSafeActionClient } from '#safe-action'

export const actionClient = createSafeActionClient({
  handleServerError(error) {
    console.error('Action failed:', error)
    return 'Something went wrong. Please try again.'
  },
})

export const loggedActionClient = actionClient.use(async ({ ctx, next, metadata }) => {
  const started = Date.now()
  const result = await next({ ctx })
  console.info('Action completed', metadata.name, Date.now() - started)
  return result
})

handleServerError maps unexpected exceptions to a public message. Intentional ActionError messages are returned directly; field errors thrown by returnValidationErrors() remain field errors. Do not expose raw database errors, credentials, or stack traces in a public mapper.

Compose context

const identifiedClient = actionClient.use(async ({ ctx, next }) =>
  next({ ctx: { ...ctx, requestLabel: 'example' } }),
)

const contextualClient = identifiedClient.use(async ({ ctx, next }) =>
  next({ ctx: { ...ctx, labelLength: ctx.requestLabel.length } }),
)

next({ ctx }) replaces context. Spread ...ctx when extending it. The handler receives the final context type. Call next() exactly once to continue, or throw to reject. Authentication and ownership checks are covered in the authentication recipe.

Copyright © 2026