
Astro Actions Has a Free API: Type-Safe Server Functions with Built-in Validation
Why Astro Actions? Astro Actions let you define type-safe server functions that you call directly from your client code. Think tRPC but built into the framework - with Zod validation, automatic error handling, and zero boilerplate. Define an Action // src/actions/index.ts import { defineAction } from ' astro:actions ' ; import { z } from ' astro:schema ' ; export const server = { createPost : defineAction ({ accept : ' json ' , input : z . object ({ title : z . string (). min ( 1 ). max ( 200 ), body : z . string (). min ( 10 ), tags : z . array ( z . string ()). optional (), }), handler : async ( input , context ) => { const post = await db . posts . create ({ data : { ... input , authorId : context . locals . userId }, }); return { id : post . id , slug : post . slug }; }, }), deletePost : defineAction ({ accept : ' json ' , input : z . object ({ id : z . string (). uuid () }), handler : async ({ id }) => { await db . posts . delete ({ where : { id } }); return { success : true }; },
Continue reading on Dev.to JavaScript
Opens in a new tab



