Endpoints
Guidelines for creating API routes and custom endpoints in Astro.
astro
## Astro Endpoints Guidelines
1. Purpose: Create non-HTML responses like JSON data, RSS feeds, dynamic images, or full API routes.
2. Location: Place `.js` or `.ts` files inside the `src/pages/` directory.
3. Routing & Naming:
- The file path determines the route (e.g., `src/pages/api/users.json.ts` becomes `/api/users.json`).
- The extension in the filename dictates the output file's extension (e.g., `.json.ts` -> `.json`, `.png.ts` -> `.png`).
4. Core Structure:
- Export named functions corresponding to HTTP methods (e.g., `export function GET(...)`, `export function POST(...)`, `export function DELETE(...)`, `export const ALL = (...)`).
- Use `import type { APIRoute } from 'astro';` for typing these functions (e.g., `export const GET: APIRoute = (...) => { ... }`).
- Each function receives a context object (similar to `Astro` global) containing `params`, `request`, `cookies`, `redirect`, etc.
- Functions must return a standard Web `Response` object (e.g., `return new Response(JSON.stringify({ data }), { status: 200, headers: { 'Content-Type': 'application/json' } });`).
5. Static Endpoints (Default Build Behavior):
- The `GET` function runs _at build time_ to generate a static file. Other methods (POST, etc.) are not applicable.
- Dynamic Routes: Use `[param]` syntax in filenames (e.g., `src/pages/users/[id].json.ts`). Requires exporting `getStaticPaths()` to define the paths to pre-render at build time.
- Context:
- `params`: Contains parameters defined in `getStaticPaths`.
- `request`: Limited; primarily `request.url` is useful.
6. Server Endpoints (API Routes - Requires SSR/Hybrid Mode):
- Requires `output: 'server'` or `output: 'hybrid'` in `astro.config.mjs`.
- For hybrid/static sites, opt-out of pre-rendering for the specific endpoint file: `export const prerender = false;`.
- Functions run _on request_ time (server-side).
- All HTTP Methods: Supports `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `ALL`, etc. Export functions for the methods you need to handle. Astro calls the matching function based on the incoming request method.
- `ALL` serves as a fallback for methods without a specific exported function.
- Dynamic Routes: `params` are available directly from the requested URL (e.g., `Astro.params.id` or `context.params.id`) without needing `getStaticPaths`.
- Context:
- `request`: A full standard `Request` object. Access headers (`request.headers.get(...)`), body (`await request.json()`, `await request.formData()`), method (`request.method`), etc.
- `redirect`: A function `redirect('/new-path', status?)` to perform server-side redirects (similar to `Astro.redirect`).
- `cookies`: Access/set cookies using `context.cookies.get(...)` and `context.cookies.set(...)`.
7. Response Object:
- Use the standard `Response` constructor.
- Set body, status code (`status`), and headers (`headers`).
- For binary data (like images), pass an `ArrayBuffer` or `Buffer` as the body and set the correct `Content-Type` header.
Reference: [Astro Endpoints Docs](mdc:https:/docs.astro.build/en/guides/endpoints)