Astro Routing: File-based Routing และ Dynamic Routes

#astro12 เม.ย. 2569

File-based Routing

Astro ใช้ file-based routing เหมือน Next.js ทุกไฟล์ใน src/pages/ กลายเป็น route อัตโนมัติ

src/pages/
  index.astro        → /
  about.astro        → /about
  blog/
    index.astro      → /blog
    [slug].astro     → /blog/:slug
  [...path].astro    → /anything/nested

Static Routes

---
// src/pages/about.astro
---

<html>
  <body>
    <h1>เกี่ยวกับเรา</h1>
  </body>
</html>

Dynamic Routes

---
// src/pages/blog/[slug].astro
export async function getStaticPaths() {
  return [
    { params: { slug: 'post-1' }, props: { title: 'บทความ 1' } },
    { params: { slug: 'post-2' }, props: { title: 'บทความ 2' } },
  ];
}

const { slug } = Astro.params;
const { title } = Astro.props;
---

<h1>{title}</h1>
<p>Slug: {slug}</p>

Rest Parameters

---
// src/pages/docs/[...path].astro
const { path } = Astro.params;
// /docs/a/b/c → path = 'a/b/c'
---

Redirect

---
// src/pages/old-page.astro
return Astro.redirect('/new-page', 301);
---

API Routes

// src/pages/api/users.ts
import type { APIRoute } from 'astro';

export const GET: APIRoute = async ({ request }) => {
  const users = await fetchUsers();
  return new Response(JSON.stringify(users), {
    headers: { 'Content-Type': 'application/json' }
  });
};

export const POST: APIRoute = async ({ request }) => {
  const body = await request.json();
  // สร้าง user ใหม่
  return new Response(JSON.stringify({ success: true }), {
    status: 201
  });
};

Middleware

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

export const onRequest = defineMiddleware(async (context, next) => {
  const token = context.cookies.get('token');

  if (context.url.pathname.startsWith('/admin') && !token) {
    return context.redirect('/login');
  }

  return next();
});

สรุป

Astro routing ใช้งานง่ายมาก file structure ตรงกับ URL structure ทำให้เข้าใจได้ทันที รองรับทั้ง static และ dynamic routes ครับ