Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท SSR, Adapters and Endpoints

Astro Actions: Type-Safe Forms and Server Functions

Define type-safe server functions with Astro Actions, validate input with Zod, handle HTML forms without JavaScript and call actions from islands.

Writing an endpoint, parsing the body, validating it, returning error JSON and then calling it with fetch is the same boilerplate every time. Astro Actions package that flow: you define a server function with an input schema, and call it from the browser or from a plain HTML form as if it were a normal function, with types and validation errors included.

Define an action

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

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

export const server = {
  subscribe: defineAction({
    accept: 'form',
    input: z.object({
      email: z.string().email('Enter a valid email'),
      topics: z.array(z.string()).min(1, 'Pick at least one topic'),
      consent: z.boolean().refine((v) => v, 'You must agree'),
    }),
    handler: async (input, context) => {
      if (await alreadySubscribed(input.email)) {
        throw new ActionError({ code: 'CONFLICT', message: 'You are already subscribed.' });
      }
      await saveSubscriber(input.email, input.topics);
      return { ok: true };
    },
  }),

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

Pieces:

  • defineAction({ input, handler }): input is a Zod schema (use z from astro:schema); handler receives the validated data and the same context as endpoints (cookies, locals, request).
  • accept: 'form' makes the action read FormData and convert it to the schema's shape (booleans from checkboxes, numbers, arrays from repeated names). The default is 'json'.
  • ActionError carries an HTTP-style code (BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, CONFLICT, INTERNAL_SERVER_ERROR, ...) and a message.

Actions run only on the server. They need an adapter and are exposed at /_actions/...; a prerendered page can call them, as the action itself runs per request.

Calling from a script or island

TypeScript
import { actions, isInputError } from 'astro:actions';

const { data, error } = await actions.likePost({ postId: 'hello-astro' });

if (error) {
  if (isInputError(error)) {
    console.log(error.fields);        // { postId: ['Required'] }
  } else {
    console.log(error.code, error.message);
  }
} else {
  console.log(data.likes);
}

You always get { data, error }; nothing throws. TypeScript knows the shape of data and the input type from the schema, with no code generation. Add .orThrow() (await actions.likePost(...).orThrow()) if you prefer exceptions.

Forms that work without JavaScript

With accept: 'form', a regular HTML form can post directly to the action:

ASTRO
---
import { actions } from 'astro:actions';

const result = Astro.getActionResult(actions.subscribe);
const errors = result?.error?.fields ?? {};
---
<form method="POST" action={actions.subscribe}>
  <label>Email <input type="email" name="email" required /></label>
  {errors.email && <p class="error">{errors.email[0]}</p>}

  <fieldset>
    <legend>Topics</legend>
    <label><input type="checkbox" name="topics" value="news" /> News</label>
    <label><input type="checkbox" name="topics" value="tips" /> Tips</label>
  </fieldset>

  <label><input type="checkbox" name="consent" /> I agree</label>
  <button>Subscribe</button>
</form>

{result && !result.error && <p>Thanks! Check your inbox.</p>}

The browser submits the form, the server runs the action, then redirects back to the page where Astro.getActionResult() returns the result. Everything works with JavaScript disabled, and Astro keeps the user on the same URL without a "resubmit form?" prompt. This is progressive enhancement: the base behaviour needs no JS, and JS only improves it.

To enhance with JavaScript (no reload), intercept the submit:

ASTRO
<script>
  import { actions } from 'astro:actions';
  const form = document.querySelector('form');
  form?.addEventListener('submit', async (e) => {
    e.preventDefault();
    const { data, error } = await actions.subscribe(new FormData(form));
    if (error) console.error(error.message);
    else form.reset();
  });
</script>

Calling actions from other server code

On the server, use Astro.callAction(actions.likePost, { postId }) or context.callAction from middleware and endpoints. To protect an action, check context.locals inside the handler, as in likePost above.

When to use actions versus endpoints

Use actions for Use endpoints for
Your own forms and button clicks Public APIs for other clients
Typed calls from your frontend Webhooks, RSS, files, images
Built-in validation Custom methods, headers, streaming

Actions are great for the site's own mutations; endpoints stay the right tool for URLs that outside systems call.

Security notes

  • Validate everything in the schema: lengths (.max(500)), formats, enums.
  • Authenticate inside handlers, not just on pages.
  • Origin checking applies like for other POSTs.
  • Don't return internal error details; throw ActionError with a safe message.

Try it: a defineAction stand-in

A minimal imitation: an input schema describing types, validation producing field errors, and a result of { data, error }.

JS Validated actions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: FormData to typed input

With accept: 'form', Astro turns FormData into the object your schema expects. This stand-in shows that conversion, including repeated names and checkboxes.

JS FormData to object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you define Astro Actions?

    The server object exported from src/actions/index.ts holds all actions, which are then available through astro:actions.
  2. 2. What does an action call return on the client?

    Calls resolve to { data, error } so you handle failures without try/catch; .orThrow() offers the exception style.
  3. 3. Why does accept: 'form' matter?

    The action reads FormData, and Astro redirects back so getActionResult can show the outcome.
  4. 4. Where should authorisation be checked for a like-post action?

    Actions are callable endpoints, so the handler must verify the user itself.

Summary

  • Actions are typed, validated server functions defined with defineAction and a Zod schema.
  • Calls return { data, error }; isInputError exposes field errors.
  • accept: 'form' supports no-JS forms with Astro.getActionResult.
  • Use ActionError for safe, coded failures and check auth inside handlers.
  • Endpoints remain best for public or non-form APIs.

Next: Performance and Core Web Vitals