Understanding Astro API Routes
Astro API routes use theAPIRoute type and receive an APIContext object with request information. Routes are defined by exporting HTTP method handlers (GET, POST, etc.).
APIRoute Type
TheAPIRoute type defines the signature for API endpoint handlers:
APIContext Properties
TheAPIContext object provides access to:
request- The incoming Request objectparams- Route parameters from dynamic routesclientAddress- The client’s IP addresssite- The site configurationurl- The request URLgenerator- Astro version informationcookies- Cookie management utilitieslocals- Local variables for the request
GET /edge.json
Returns metadata about the current request, including client information and server context.Edge Function endpoint that returns request metadata
Request
No parameters required. Simply make a GET request to/edge.json.
Response
Current server timestamp
The client’s IP address
The site URL from Astro configuration
The full request URL
Astro version information
The client’s User-Agent header
Implementation
Location:src/pages/edge.json.ts
Key Features
- Edge Runtime: Runs on Vercel Edge Functions for low latency
- Dynamic Rendering:
prerender = falseensures the route is server-rendered - Caching Strategy: Uses
s-maxage=10with stale-while-revalidate for optimal performance - Request Context: Demonstrates accessing various APIContext properties
Example Response
POST /api/revalidate
Triggers revalidation of cached content by tag. Used for on-demand ISR (Incremental Static Regeneration).Revalidate cached content by tag
Request
The cache tag to revalidate
Request Body Example
Response
The tag that was revalidated (echoed back)
Implementation
Location:src/pages/api/revalidate.ts
Key Features
- On-Demand Revalidation: Triggers cache invalidation for specific tags
- Bypass Token: Uses
x-prerender-revalidateheader for authentication - Async Handler: Demonstrates async/await pattern for request body parsing
Usage Example
Security Considerations
Production Implementation
Production Implementation
In production, you should:
- Use environment variables for the bypass token
- Validate the token from request headers
- Implement rate limiting
- Add proper error handling
Setting Prerender Mode
Both routes useexport const prerender = false to disable static generation:
- Routes are server-rendered on each request
- Access to runtime request data (headers, IP, etc.)
- Deployment as Vercel Edge Functions