🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Server Rendering••By Komal Nakrani

Astro Actions: Type-Safe Forms and Mutations Guide

Astro Actions guide: define type-safe server functions with Zod, handle HTML forms and JSON calls, show field errors, throw ActionError, and avoid resubmits.

#Astro#Astro Actions#Forms#SSR

Astro Actions are type-safe server functions you define in src/actions/index.ts with defineAction(). Each action declares a Zod input schema and a handler; Astro creates the endpoint, validates input, and lets you call it from an HTML form (action={actions.name}), from browser JavaScript (await actions.name(input)), or from server code. They replace hand-written API endpoints for forms and mutations, and they need an adapter because the handler runs on the server.

This guide covers Astro Actions in Astro 7: defining actions, form and JSON input, returning errors, showing field-level validation, avoiding duplicate submissions, and security.

Key Takeaways

  • Export a server object from src/actions/index.ts; each key becomes actions.<key>.
  • accept: 'form' parses FormData against your schema; the default is JSON.
  • Calls return { data, error } instead of throwing; use .orThrow() when you want exceptions.
  • isInputError(error) gives you error.fields with messages per field.
  • Actions need an adapter and an on-demand route for HTML form submissions.

Why use Astro Actions

Without actions, a form in Astro needs an API endpoint: parse the request body, validate each field by hand, return JSON or a redirect, then write client code that calls the endpoint and handles errors. Types between the endpoint and the caller aren’t connected, so a renamed field breaks silently.

Astro Actions handle that plumbing:

  • One definition. The input schema, handler and return type live in one place.
  • Validation. Input is checked against a Zod schema before your handler runs.
  • Typed calls. actions.subscribe() knows its input and output types in TypeScript.
  • Standard errors. ActionError maps codes like UNAUTHORIZED to HTTP statuses.
  • Works without JavaScript. Forms can post directly to an action and degrade gracefully.

Setting up Astro Actions

Actions run on the server, so the project needs an adapter:

npx astro add node

Pages stay prerendered by default, so only the pages that receive form posts need export const prerender = false. If you skip the adapter, the build stops with “Actions must be used with server output”; the fix for that error explains it, and Astro adapters explained helps you pick one.

Defining your first action

Create src/actions/index.ts and export a server object:

// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';

export const server = {
  newsletter: defineAction({
    accept: 'form',
    input: z.object({
      email: z.email(),
      topics: z.array(z.string()).default([]),
      consent: z.boolean(),
    }),
    handler: async ({ email, topics, consent }, context) => {
      if (!consent) {
        throw new ActionError({ code: 'BAD_REQUEST', message: 'Please accept the privacy policy.' });
      }
      await addSubscriber({ email, topics });
      return { email };
    },
  }),

  likePost: defineAction({
    input: z.object({ postId: z.string() }),
    handler: async ({ postId }, context) => {
      const user = context.locals.user;
      if (!user) throw new ActionError({ code: 'UNAUTHORIZED' });
      const likes = await incrementLikes(postId, user.id);
      return { likes };
    },
  }),
};

addSubscriber and incrementLikes stand in for your own database or API calls. A few details:

  • accept: 'form' tells Astro to parse a FormData body. Astro converts form fields using the schema: checkboxes become booleans, repeated fields become arrays, number fields become numbers.
  • Without accept, the action expects JSON, which suits calls from scripts.
  • The second handler argument is a context object with cookies, locals, request, url, session and more, so actions can check authentication set by middleware.
  • Return values must be serializable. Returning a class instance or function causes “Action handler returned invalid data.”

You can group actions into nested objects (export const server = { blog: { like, comment } }) and call them as actions.blog.like.

Calling Astro Actions from an HTML form

The most reliable way to use an action is a plain form. It works before JavaScript loads and without JavaScript at all:

---
// src/pages/newsletter.astro
import { actions, isInputError } from 'astro:actions';
import BaseLayout from '../layouts/BaseLayout.astro';

export const prerender = false;

const result = Astro.getActionResult(actions.newsletter);
const fieldErrors = isInputError(result?.error) ? result.error.fields : {};
---
<BaseLayout title="Newsletter" description="Get new articles by email.">
  {result?.data && <p role="status">Subscribed as {result.data.email}.</p>}
  {result?.error && !isInputError(result.error) && <p role="alert">{result.error.message}</p>}

  <form method="POST" action={actions.newsletter}>
    <label for="email">Email</label>
    <input id="email" name="email" type="email" required aria-describedby="email-error" />
    {fieldErrors.email && <p id="email-error">{fieldErrors.email.join(', ')}</p>}

    <fieldset>
      <legend>Topics</legend>
      <label><input type="checkbox" name="topics" value="astro" /> Astro</label>
      <label><input type="checkbox" name="topics" value="performance" /> Performance</label>
    </fieldset>

    <label><input type="checkbox" name="consent" /> I accept the privacy policy</label>
    <button type="submit">Subscribe</button>
  </form>
</BaseLayout>

action={actions.newsletter} renders a URL with a query string that tells Astro which action to run. When the form posts, Astro runs the action and renders the same page with the result available through Astro.getActionResult(). The page must be on demand, because it renders differently after each submission.

Handling validation and errors

Every action call returns a result object instead of throwing:

Result Meaning
{ data } The handler returned successfully
{ error } where isInputError(error) is true Input failed the Zod schema; error.fields maps each field to messages
{ error } with error.code The handler threw an ActionError, or an unexpected error occurred (INTERNAL_SERVER_ERROR)

ActionError accepts standard HTTP codes such as BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, CONFLICT, TOO_MANY_REQUESTS and INTERNAL_SERVER_ERROR. Astro sets the matching HTTP status on the response, so UNAUTHORIZED returns a 401.

Customize validation messages in the schema itself, where they’re defined once and appear in error.fields:

// src/actions/index.ts (excerpt)
input: z.object({
  name: z.string().min(2, 'Enter at least 2 characters'),
  email: z.email('Enter a valid email address'),
}),

Calling Astro Actions from client-side JavaScript

For interactions that shouldn’t reload the page (likes, inline edits, live forms), import actions in a script. The call is typed and returns the same result object:

---
// src/components/LikeButton.astro
const { postId } = Astro.props;
---
<button class="like" data-post-id={postId}>Like</button>

<script>
  import { actions } from 'astro:actions';

  document.querySelectorAll<HTMLButtonElement>('.like').forEach((button) => {
    button.addEventListener('click', async () => {
      const { data, error } = await actions.likePost({ postId: button.dataset.postId! });
      if (error) {
        button.textContent = error.code === 'UNAUTHORIZED' ? 'Sign in to like' : 'Try again';
        return;
      }
      button.textContent = `Liked (${data.likes})`;
    });
  });
</script>

The component and its page can be prerendered; only the action call reaches the server. For form actions called from scripts, pass new FormData(form) as the input.

If you’d rather use try/catch, call actions.likePost.orThrow(input), which returns the data directly and throws on error. Actions also work inside React, Vue, Svelte and other framework islands with the same import.

Calling actions from server code

From an .astro page or another server context, use Astro.callAction():

---
// src/pages/posts/[id].astro (excerpt)
import { actions } from 'astro:actions';
export const prerender = false;

const { data } = await Astro.callAction(actions.likePost, { postId: Astro.params.id! });
---

This runs the handler directly with the current request’s context, without an HTTP round trip. For logic shared across many pages, a plain function imported by both the action and the page is often simpler.

Avoiding duplicate submissions on refresh

When a form posts to a page, the browser holds that POST. If the visitor refreshes, the browser offers to resubmit, and the action can run twice. The standard fix is Post/Redirect/Get: handle the action in middleware, store the result, and redirect to a GET.

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getActionContext } from 'astro:actions';

export const onRequest = defineMiddleware(async (context, next) => {
  if (context.isPrerendered) return next();

  const { action, setActionResult, serializeActionResult } = getActionContext(context);

  const stored = await context.session?.get('actionResult');
  if (stored) {
    setActionResult(stored.name, stored.result);
    context.session?.delete('actionResult');
    return next();
  }

  if (action?.calledFrom === 'form') {
    const result = await action.handler();
    context.session?.set('actionResult', {
      name: action.name,
      result: serializeActionResult(result),
    });
    return context.redirect(context.originPathname);
  }

  return next();
});

This uses Astro sessions to carry the result across the redirect, so the session driver for your adapter must be configured. After the redirect, Astro.getActionResult() reads the stored result as before and a refresh is a harmless GET.

Security considerations

  • Origin checks. Astro’s security.checkOrigin option is on by default for on-demand pages, which rejects cross-site form posts. Leave it on.
  • Authorize in the handler. An action is a public endpoint. Check context.locals.user or the session in every handler that changes data; hiding a button isn’t access control.
  • Validate everything. The schema is your first defense; keep it strict, with lengths and formats, not just z.string().
  • Rate limit sensitive actions. Login, signup and contact actions attract abuse. Use your host’s rate limiting or a counter in middleware.
  • Keep secrets in the handler. API keys used inside handlers stay on the server. Read them with astro:env/server; see the environment variables guide.

Astro Actions versus endpoints and form services

Astro Actions API endpoint (src/pages/api/*.ts) Third-party form service
Input validation Built in (Zod) Write it yourself Provider’s rules
Type-safe calls Yes No No
HTML form support Yes, with results on the page Manual Yes
Needs an adapter Yes Yes (if not prerendered) No
Good for webhooks and public APIs Not ideal Yes No

Use actions for anything your own pages call. Use endpoints for webhooks, public APIs and responses that aren’t JSON, such as files or feeds. Use a form service when the site must stay fully static; the contact forms guide compares all the options.

Komal themes are static and include forms as plain HTML, so connecting a theme’s contact or signup form to an action means adding an adapter, an action, and prerender = false on that page. Browse Astro themes, or read the Astro SSR guide for the other server features. The official reference is Astro’s Actions guide.

FAQ

What are Astro Actions?

Astro Actions are server functions defined with defineAction() that validate input with a Zod schema and can be called from HTML forms, browser scripts or server code with full type safety. Astro creates the endpoints and handles parsing, validation and error responses.

Do Astro Actions work on a static site?

They need an adapter, because the handler runs on a server. The rest of the site can stay prerendered. Pages that only call actions from client scripts can be static; pages that receive HTML form posts need export const prerender = false.

How do I show validation errors with Astro Actions?

Check the result with isInputError(result.error). If it’s true, result.error.fields maps each field name to an array of messages from your Zod schema, which you render next to the matching input.

What’s the difference between Astro Actions and API endpoints?

Actions add input validation, typed calls and form handling on top of a server function. Endpoints are raw request handlers that return any Response. Actions suit forms and mutations from your own pages; endpoints suit webhooks, public APIs and non-JSON responses.

Can I use Astro Actions with React?

Yes. Import actions from astro:actions inside a React component (or Vue, Svelte, Solid) used as a client island, and call await actions.name(input). The call is typed the same way as in an Astro script.