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".
What this skill does
# 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 in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.