Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/vercel-edge-functions

@0d57af8
Run it yourself

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".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/vercel-edge-functions

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

SKILL.md

≈88 tokens for metadata: the name and description. ≈1.8k when used: this file.

Description uses 4.4% of example budget

Before choosing a Skill, your Agent reads its name and description. All available Skills share that space.

  • A shorter description leaves more room for other Skills. This entry exceeds our 1% size suggestion.

In our Claude Code example, all Skill names and descriptions share 8,000 characters. This Skill uses ≈353 characters, or 4.4%.

The 1% threshold is a size suggestion. Longer descriptions can still fit.

Your model, settings, and other Skills decide how much text your Agent can read.

Example settings and source

The example uses a 200k-token context and default Claude Code settings. The count includes the name, description, separators, and when_to_use when present. Codex also counts local file paths.

Skit's source and limits: Codex 0.160.1, Claude Code 2.1.292.

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

// 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:

// 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:

// 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

// 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)

// 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

Examples

Roll out edge authorization middleware safely

Implement an allow-listed middleware matcher that excludes static assets and health checks, and validate its Web API-only dependencies with the Edge runtime in preview. Send synthetic signed and unsigned requests from at least two regions, verify that unauthorized requests receive the intended response without logging credentials, and measure added latency. Release behind a reversible configuration flag; if legitimate traffic is blocked, disable the flag or restore the previous deployment before changing the policy.

Resources

Next Steps

For common errors, see vercel-common-errors.

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts8mo3 checks · Risk SAFE
  • Gen Agent Trust Hub8mo

    No security issues detected. The skill provides a framework for deploying Vercel Edge Functions using standard tools without any malicious instructions or suspicious patterns.

  • Socket8mo

    No alerts

  • Snyk8mo

    Risk: LOW · No issues

Signed by skilld at 0d57af8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 3 months ago
What it can do
Reads files Edits files Runs commands
version
1.18.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
[
  "saas",
  "vercel",
  "edge",
  "serverless",
  "performance"
]
All 6 allowed tools
ReadWriteEditBash(vercel:*)Bash(npm:*)Grep
Other metadata
compatibility
Designed for Claude Code

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/vercel-edge-functions