Overview
Vercel Edge Functions allow you to create API endpoints that run at the edge, close to your users. They’re perfect for building dynamic APIs, handling webhooks, and processing data in real-time.
Edge Functions run on Vercel’s Edge Network using a lightweight runtime, providing low-latency responses worldwide.
Creating an Edge Function
Create an API endpoint by exporting an HTTP method handler:
import type { APIContext , APIRoute } from 'astro'
export const prerender = false
export const GET : APIRoute = ( context : APIContext ) => {
return new Response (
JSON . stringify ({
time: new Date (),
clientAddress: context . clientAddress ,
site: context . site ,
url: context . url ,
generator: context . generator ,
userAgent: context . request . headers . get ( 'user-agent' ),
}),
{
status: 200 ,
headers: {
'Content-Type' : 'application/json' ,
'Cache-Control' : 's-maxage=10, stale-while-revalidate' ,
},
}
)
}
The .json.ts extension tells Astro this is an API endpoint that returns JSON data.
APIContext
The APIContext object provides access to request information and utilities:
clientAddress
request
site
url
params
// Get the client's IP address
context . clientAddress
HTTP Methods
Support multiple HTTP methods by exporting handlers:
import type { APIRoute } from 'astro'
export const prerender = false
// Handle GET requests
export const GET : APIRoute = async ( context ) => {
const users = await fetchUsers ()
return new Response ( JSON . stringify ( users ), {
status: 200 ,
headers: { 'Content-Type' : 'application/json' },
})
}
// Handle POST requests
export const POST : APIRoute = async ( context ) => {
const data = await context . request . json ()
const user = await createUser ( data )
return new Response ( JSON . stringify ( user ), {
status: 201 ,
headers: { 'Content-Type' : 'application/json' },
})
}
// Handle DELETE requests
export const DELETE : APIRoute = async ( context ) => {
const { id } = await context . request . json ()
await deleteUser ( id )
return new Response ( null , { status: 204 })
}
Control caching and content type with response headers:
return new Response ( JSON . stringify ( data ), {
status: 200 ,
headers: {
'Content-Type' : 'application/json' ,
'Cache-Control' : 's-maxage=10, stale-while-revalidate' ,
'Access-Control-Allow-Origin' : '*' ,
},
})
Content-Type
Cache-Control
CORS
Specify the response format: 'Content-Type' : 'application/json'
'Content-Type' : 'text/html'
'Content-Type' : 'text/plain'
Control caching behavior: 's-maxage=10, stale-while-revalidate'
'public, max-age=3600'
'no-cache, no-store'
Enable cross-origin requests: 'Access-Control-Allow-Origin' : '*'
'Access-Control-Allow-Methods' : 'GET, POST'
'Access-Control-Allow-Headers' : 'Content-Type'
Dynamic Routes
Create endpoints with dynamic parameters:
src/pages/api/users/[id].ts
import type { APIRoute } from 'astro'
export const prerender = false
export const GET : APIRoute = async ( context ) => {
const { id } = context . params
const user = await fetchUser ( id )
if ( ! user ) {
return new Response ( JSON . stringify ({ error: 'User not found' }), {
status: 404 ,
headers: { 'Content-Type' : 'application/json' },
})
}
return new Response ( JSON . stringify ( user ), {
status: 200 ,
headers: { 'Content-Type' : 'application/json' },
})
}
Error Handling
Handle errors gracefully with appropriate status codes:
export const POST : APIRoute = async ( context ) => {
try {
const data = await context . request . json ()
// Validate input
if ( ! data . email ) {
return new Response (
JSON . stringify ({ error: 'Email is required' }),
{ status: 400 , headers: { 'Content-Type' : 'application/json' } }
)
}
const result = await createUser ( data )
return new Response ( JSON . stringify ( result ), {
status: 201 ,
headers: { 'Content-Type' : 'application/json' },
})
} catch ( error ) {
return new Response (
JSON . stringify ({ error: 'Internal server error' }),
{ status: 500 , headers: { 'Content-Type' : 'application/json' } }
)
}
}
Always validate input and handle errors to prevent exposing sensitive information.
Global Distribution : Edge Functions run on Vercel’s global network
Low Latency : Execution close to users reduces response time
Auto-Scaling : Automatically scales based on traffic
Lightweight Runtime : Fast cold starts and efficient execution
Use Cases
API Endpoints : Build RESTful APIs for your application
Webhooks : Handle incoming webhooks from third-party services
Data Transformation : Process and transform data on-the-fly
Authentication : Validate tokens and manage sessions
Proxying : Forward requests to external APIs with custom logic
Real-time Data : Fetch and return fresh data on each request
Next Steps
Middleware Add middleware to process requests
ISR Combine with ISR for cached API responses