vercel-edge-functions
Build and deploy Vercel Edge Functions for ultra-low latency at the edge. Use when creating API routes with minimal latency, geolocation-based routing, A/B testing, or authentication at the edge. Trigger with phrases like "vercel edge function", "vercel edge runtime", "deploy edge function", "vercel middleware", "@vercel/edge".
Best use case
vercel-edge-functions is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Build and deploy Vercel Edge Functions for ultra-low latency at the edge. Use when creating API routes with minimal latency, geolocation-based routing, A/B testing, or authentication at the edge. Trigger with phrases like "vercel edge function", "vercel edge runtime", "deploy edge function", "vercel middleware", "@vercel/edge".
Teams using vercel-edge-functions should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/vercel-edge-functions/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How vercel-edge-functions Compares
| Feature / Agent | vercel-edge-functions | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Build and deploy Vercel Edge Functions for ultra-low latency at the edge. Use when creating API routes with minimal latency, geolocation-based routing, A/B testing, or authentication at the edge. Trigger with phrases like "vercel edge function", "vercel edge runtime", "deploy edge function", "vercel middleware", "@vercel/edge".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Vercel Edge Functions
## Overview
Edge Functions run on Vercel's Edge Network (V8 isolates) close to the user with no cold starts. They use Web Standard APIs (Request, Response, fetch) instead of Node.js APIs. Ideal for authentication, A/B testing, geolocation routing, and low-latency API responses.
## Prerequisites
- Completed `vercel-install-auth` setup
- Familiarity with Web APIs (Request/Response)
- Node.js 18+ for local development
## Instructions
### Step 1: Create an Edge Function
```typescript
// api/edge-hello.ts
// Export `runtime = 'edge'` to run on the Edge Runtime
export const config = { runtime: 'edge' };
export default function handler(request: Request): Response {
return new Response(
JSON.stringify({
message: 'Hello from the Edge!',
region: request.headers.get('x-vercel-ip-city') ?? 'unknown',
timestamp: Date.now(),
}),
{
status: 200,
headers: { 'Content-Type': 'application/json' },
}
);
}
```
### Step 2: Edge Function with Geolocation
Vercel injects geolocation headers into every edge request:
```typescript
// api/geo.ts
export const config = { runtime: 'edge' };
export default function handler(request: Request): Response {
const city = request.headers.get('x-vercel-ip-city') ?? 'unknown';
const country = request.headers.get('x-vercel-ip-country') ?? 'unknown';
const region = request.headers.get('x-vercel-ip-country-region') ?? 'unknown';
const latitude = request.headers.get('x-vercel-ip-latitude');
const longitude = request.headers.get('x-vercel-ip-longitude');
return Response.json({
city: decodeURIComponent(city),
country,
region,
coordinates: latitude && longitude ? { lat: latitude, lng: longitude } : null,
});
}
```
### Step 3: Edge Middleware (middleware.ts)
Middleware runs before every request and can rewrite, redirect, or add headers:
```typescript
// middleware.ts (must be at project root or src/)
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
// Example 1: Redirect based on country
const country = request.geo?.country ?? 'US';
if (country === 'DE') {
return NextResponse.redirect(new URL('/de', request.url));
}
// Example 2: A/B testing with cookies
const bucket = request.cookies.get('ab-bucket')?.value;
if (!bucket) {
const response = NextResponse.next();
response.cookies.set('ab-bucket', Math.random() > 0.5 ? 'a' : 'b');
return response;
}
// Example 3: Add security headers
const response = NextResponse.next();
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
return response;
}
// Only run on specific paths — skip static assets
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
```
### Step 4: Edge Function with Streaming
```typescript
// api/stream.ts
export const config = { runtime: 'edge' };
export default function handler(): Response {
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
for (let i = 0; i < 5; i++) {
controller.enqueue(encoder.encode(`data: chunk ${i}\n\n`));
await new Promise(r => setTimeout(r, 500));
}
controller.enqueue(encoder.encode('data: [DONE]\n\n'));
controller.close();
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
}
```
### Step 5: Edge Config (Key-Value Store)
```typescript
// api/feature-flags.ts
import { get } from '@vercel/edge-config';
export const config = { runtime: 'edge' };
export default async function handler(): Promise<Response> {
// Read from Edge Config — sub-millisecond reads at the edge
const maintenanceMode = await get<boolean>('maintenance_mode');
const featureFlags = await get<Record<string, boolean>>('feature_flags');
if (maintenanceMode) {
return Response.json({ status: 'maintenance' }, { status: 503 });
}
return Response.json({ features: featureFlags });
}
```
Install: `npm install @vercel/edge-config`
## Edge vs Serverless Comparison
| Feature | Edge Runtime | Node.js (Serverless) |
|---------|-------------|---------------------|
| Cold start | None (~0ms) | 250ms–1s+ |
| Max duration | 30s (Hobby), 5min (Pro) | 10s (Hobby), 5min (Pro) |
| Max size | 1 MB (after gzip) | 250 MB (unzipped) |
| APIs available | Web Standard APIs | Full Node.js API |
| npm packages | Limited (no native modules) | All npm packages |
| Global deployment | Automatic | Single region default |
| Use case | Auth, routing, A/B, geo | Database queries, heavy compute |
## Available Web APIs in Edge Runtime
`fetch`, `Request`, `Response`, `Headers`, `URL`, `URLSearchParams`, `TextEncoder`, `TextDecoder`, `ReadableStream`, `WritableStream`, `TransformStream`, `crypto`, `atob`, `btoa`, `structuredClone`, `setTimeout`, `setInterval`, `AbortController`
**NOT available**: `fs`, `path`, `child_process`, `net`, `http`, `dns`, native Node.js modules
## Output
- Edge Function deployed globally with zero cold starts
- Geolocation-based routing using Vercel's injected headers
- Middleware running authentication and A/B tests at the edge
- Streaming responses for real-time data delivery
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| `EDGE_FUNCTION_INVOCATION_FAILED` | Runtime error in edge function | Check logs — no `try/catch` around async code |
| `Dynamic Code Evaluation not allowed` | Using `eval()` or `new Function()` | Refactor to avoid dynamic code evaluation |
| `Module not found` | npm package uses Node.js APIs | Use edge-compatible alternative or switch to Node.js runtime |
| `FUNCTION_PAYLOAD_TOO_LARGE` | Edge function bundle > 1 MB | Tree-shake imports, split into smaller functions |
| `TypeError: x is not a function` | Node.js API used in edge runtime | Replace with Web Standard API equivalent |
## Resources
- [Edge Functions Documentation](https://vercel.com/docs/functions/runtimes/edge)
- [Edge Middleware](https://vercel.com/docs/functions/edge-middleware)
- [Edge Config](https://vercel.com/docs/edge-config)
- [Edge Runtime API](https://vercel.com/docs/functions/runtimes/edge)
- [Vercel Geolocation Headers](https://vercel.com/docs/headers/request-headers)
## Next Steps
For common errors, see `vercel-common-errors`.Related Skills
vercel-webhooks-events
Implement Vercel webhook handling with signature verification and event processing. Use when setting up webhook endpoints, processing deployment events, or building integrations that react to Vercel deployment lifecycle. Trigger with phrases like "vercel webhook", "vercel events", "vercel deployment.ready", "handle vercel events", "vercel webhook signature".
vercel-upgrade-migration
Upgrade Vercel CLI, Node.js runtime, and Next.js framework versions with breaking change detection. Use when upgrading Vercel CLI versions, migrating Node.js runtimes, or updating Next.js between major versions on Vercel. Trigger with phrases like "upgrade vercel", "vercel migration", "vercel breaking changes", "update vercel CLI", "next.js upgrade on vercel".
vercel-security-basics
Apply Vercel security best practices for secrets, headers, and access control. Use when securing API keys, configuring security headers, or auditing Vercel security configuration. Trigger with phrases like "vercel security", "vercel secrets", "secure vercel", "vercel headers", "vercel CSP".
vercel-sdk-patterns
Production-ready Vercel REST API patterns with typed fetch wrappers and error handling. Use when integrating with the Vercel API programmatically, building deployment tools, or establishing team coding standards for Vercel API calls. Trigger with phrases like "vercel SDK patterns", "vercel API wrapper", "vercel REST API client", "vercel best practices", "idiomatic vercel API".
vercel-reliability-patterns
Implement reliability patterns for Vercel deployments including circuit breakers, retry logic, and graceful degradation. Use when building fault-tolerant serverless functions, implementing retry strategies, or adding resilience to production Vercel services. Trigger with phrases like "vercel reliability", "vercel circuit breaker", "vercel resilience", "vercel fallback", "vercel graceful degradation".
vercel-reference-architecture
Implement a Vercel reference architecture with layered project structure and best practices. Use when designing new Vercel projects, reviewing project structure, or establishing architecture standards for Vercel applications. Trigger with phrases like "vercel architecture", "vercel project structure", "vercel best practices layout", "how to organize vercel project".
vercel-rate-limits
Handle Vercel API rate limits, implement retry logic, and configure WAF rate limiting. Use when hitting 429 errors, implementing retry logic, or setting up rate limiting for your Vercel-deployed API endpoints. Trigger with phrases like "vercel rate limit", "vercel throttling", "vercel 429", "vercel retry", "vercel backoff", "vercel WAF rate limit".
vercel-prod-checklist
Vercel production deployment checklist with rollback and promotion procedures. Use when deploying to production, preparing for launch, or implementing go-live and instant rollback procedures. Trigger with phrases like "vercel production", "deploy vercel prod", "vercel go-live", "vercel launch checklist", "vercel promote".
vercel-policy-guardrails
Implement lint rules, CI policy checks, and automated guardrails for Vercel projects. Use when setting up code quality rules, preventing secret exposure, or enforcing deployment policies for Vercel applications. Trigger with phrases like "vercel policy", "vercel lint", "vercel guardrails", "vercel best practices check", "vercel secret scan".
vercel-performance-tuning
Optimize Vercel deployment performance with caching, bundle optimization, and cold start reduction. Use when experiencing slow page loads, optimizing Core Web Vitals, or reducing serverless function cold start times. Trigger with phrases like "vercel performance", "optimize vercel", "vercel latency", "vercel caching", "vercel slow", "vercel cold start".
vercel-observability
Set up Vercel observability with runtime logs, analytics, log drains, and OpenTelemetry tracing. Use when implementing monitoring for Vercel deployments, setting up log drains, or configuring alerting for function errors and performance. Trigger with phrases like "vercel monitoring", "vercel metrics", "vercel observability", "vercel logs", "vercel alerts", "vercel tracing".
vercel-multi-env-setup
Configure Vercel across development, preview, and production environments with scoped secrets. Use when setting up per-environment configuration, managing environment-specific variables, or implementing environment isolation on Vercel. Trigger with phrases like "vercel environments", "vercel staging", "vercel dev prod", "vercel environment setup", "vercel env scoping".