ข้ามไปเนื้อหาหลัก

Astro Actions — type-safe server functions ใน Astro 5

Astro Actions ให้เรียก server-side function จาก client โดยมี type safety ครบ — input validation ด้วย Zod, return type อัตโนมัติ ไม่ต้องเขียน API route เอง

กำหนด action:

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

export const server = {
  addComment: defineAction({
    input: z.object({
      postId: z.string(),
      text:   z.string().min(1).max(500),
    }),
    handler: async ({ postId, text }) => {
      // รันบน server — ใช้ DB ได้เลย
      const comment = await db.comments.create({ postId, text });
      return { id: comment.id };
    },
  }),
};

เรียกจาก client:

---
// form-based (progressive enhancement — ทำงานแม้ JS ปิด)
import { actions } from 'astro:actions';
---

<form action={actions.addComment} method="POST">
  <input name="postId" type="hidden" value="123">
  <textarea name="text"></textarea>
  <button type="submit">ส่ง</button>
</form>

เรียกแบบ JS:

import { actions } from 'astro:actions';

const result = await actions.addComment({ postId: '123', text: 'ดีมาก' });
if (result.error) {
  console.error(result.error.message);
} else {
  console.log(result.data.id);  // type-safe
}

ต้องใช้ Astro SSR mode (output: ‘server’ หรือ ‘hybrid’) — Actions จะไม่ทำงานบน static output