Skip to main content
Actions are type-safe server functions that handle form submissions, API calls, and other backend operations. They provide automatic validation, error handling, and progressive enhancement for forms.

Defining Actions

Create actions in src/actions/index.ts by exporting a server object:
src/actions/index.ts
Actions run exclusively on the server. Client code cannot see or execute handler logic directly.

Using Actions in Forms

Call actions from forms with automatic progressive enhancement:
src/pages/newsletter.astro
Forms work without JavaScript but get enhanced with client-side validation and handling when JS is available.

Input Validation

Use Zod schemas to validate input automatically:
src/actions/index.ts

Validation Errors

Invalid input automatically returns typed errors:
src/pages/create-post.astro

Form Data Handling

For file uploads and complex forms, use accept: 'form':
src/actions/index.ts
Use in a form:

Client-Side Actions

Call actions from client-side JavaScript:
src/pages/interactive.astro
Client-side actions require JavaScript. Always provide a fallback form that works without JS.

Error Handling

Throw ActionError for expected errors:
src/actions/index.ts

Error Codes

400
Invalid request format
401
Authentication required
403
Insufficient permissions
404
Resource not found
408
Request timeout
409
Resource conflict
500
Server error

Context Object

Access request context in action handlers:
src/actions/index.ts

JSON Actions

By default, actions accept JSON input:
src/actions/index.ts
Call from client code:

Progressive Enhancement

Actions work without JavaScript but enhance when available:
src/pages/contact.astro
  • Form submits via POST request
  • Page reloads with action result
  • Result available via getActionResult()
  • Form prevents default submission
  • Action called via client-side JavaScript
  • No page reload required
  • Smooth user experience

Type Safety

Actions are fully typed:

Organizing Actions

For larger projects, organize actions into separate files:
src/actions/index.ts
src/actions/posts.ts

Advanced Patterns

Middleware

Add authentication and shared logic

API Routes

Build custom API endpoints

SSR

Server-side rendering

Type Safety

TypeScript configuration