Skip to main content
Astro Actions provide type-safe server functions that can be called from client code or Astro components.

Importing

defineAction

Define a server-side action that can be called from the client or server.
object
required
Action configuration object.
ZodSchema
Zod schema to validate input data. If accept is 'form', defaults to FormData schema.
'form' | 'json'
Type of input the action accepts. Use 'form' for form submissions or 'json' for JSON payloads.Default: 'json'
(input, context) => Promise<Output>
required
The server function that executes the action.Parameters:
Input
Parsed and validated input data matching your schema.
ActionAPIContext
Server context with request information.
AstroCookies
Cookie utilities.
Request
The original request object.
URL
Request URL.
string
Client IP address.
App.Locals
Shared locals object.

Example

Calling Actions

From Client-Side JavaScript

From Forms

From Astro Components

Use Astro.callAction() to call actions server-side:

Getting Form Results

Use Astro.getActionResult() to get results from form submissions:

Error Handling

Actions return a SafeResult object with either data or error:

Throwing Errors

Throw errors in your handler to return error responses:

Error Codes

string
HTTP-like error codes:
  • 'BAD_REQUEST' - Invalid input (400)
  • 'UNAUTHORIZED' - Authentication required (401)
  • 'FORBIDDEN' - Insufficient permissions (403)
  • 'NOT_FOUND' - Resource not found (404)
  • 'TIMEOUT' - Request timeout (408)
  • 'CONFLICT' - Resource conflict (409)
  • 'PRECONDITION_FAILED' - Precondition not met (412)
  • 'PAYLOAD_TOO_LARGE' - Request too large (413)
  • 'UNSUPPORTED_MEDIA_TYPE' - Invalid content type (415)
  • 'UNPROCESSABLE_CONTENT' - Validation failed (422)
  • 'TOO_MANY_REQUESTS' - Rate limit exceeded (429)
  • 'CLIENT_CLOSED_REQUEST' - Client cancelled (499)
  • 'INTERNAL_SERVER_ERROR' - Server error (500)
  • 'NOT_IMPLEMENTED' - Not implemented (501)
  • 'BAD_GATEWAY' - Bad gateway (502)
  • 'SERVICE_UNAVAILABLE' - Service unavailable (503)
  • 'GATEWAY_TIMEOUT' - Gateway timeout (504)

Input Validation

Input is automatically validated using the provided Zod schema:
Validation errors are returned automatically:

orThrow

Call .orThrow() to throw on errors instead of returning a result object:
This is useful for server-side code where you want exceptions instead of result objects.