Skip to content
Development
Command

/vercel-edge-function

Generate optimized Vercel Edge Functions with geolocation, authentication, and data transformation

From plugin
claude-code-templates
30k200 skills200 agents200 commands32 MCP
Install
$ npx -y skills add davila7/claude-code-templates --agent claude-code

How it fires

How this command gets triggered: by you, by Claude, or both.

  • Fires itselfClaude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/vercel-edge-function

Context preview

What this command does when you run it.

Generate optimized Vercel Edge Functions with geolocation, authentication, and data transformation

Command definition

vercel-edge-function.md
allowed-tools: Read, Write, Edit
argument-hint: [function-name] [--auth] [--geo] [--transform] [--proxy]
description: Generate optimized Vercel Edge Functions with geolocation, authentication, and data transformation

Vercel Edge Function Generator

**Function Name**: $ARGUMENTS

Current Project Analysis

Project Structure

  • Vercel config: @vercel.json (if exists)
  • Next.js config: @next.config.js
  • API routes: @app/api/ or @pages/api/
  • Middleware: @middleware.ts (if exists)

Framework Detection

  • Package.json: @package.json
  • TypeScript config: @tsconfig.json (if exists)
  • Environment variables: @.env.local (if exists)

Edge Function Implementation Strategy

1. File Structure Creation

Generate comprehensive edge function structure:

api/edge/[function-name]/
├── index.ts                    # Main edge function
├── types.ts                   # TypeScript types
├── utils.ts                   # Utility functions
├── config.ts                  # Configuration
└── __tests__/
    └── [function-name].test.ts # Unit tests

2. Base Edge Function Template

// api/edge/[function-name]/index.ts
import { NextRequest, NextResponse } from 'next/server';

export const runtime = 'edge';

export async function GET(request: NextRequest) {
  try {
    // Get geolocation data
    const country = request.geo?.country || 'Unknown';
    const city = request.geo?.city || 'Unknown';
    const region = request.geo?.region || 'Unknown';
    
    // Get request metadata
    const ip = request.headers.get('x-forwarded-for') || 'Unknown';
    const userAgent = request.headers.get('user-agent') || 'Unknown';
    const referer = request.headers.get('referer') || 'Unknown';
    
    // Process request
    const result = await processRequest({
      geo: { country, city, region },
      ip,
      userAgent,
      referer,
      url: request.url,
    });
    
    return NextResponse.json(result, {
      status: 200,
      headers: {
        'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=300',
        'Content-Type': 'application/json',
        'X-Edge-Location': region,
      },
    });
    
  } catch (error) {
    console.error('Edge function error:', error);
    
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // Validate request body
    const validationResult = validateRequestBody(body);
    if (!validationResult.valid) {
      return NextResponse.json(
        { error: 'Invalid request body', details: validationResult.errors },
        { status: 400 }
      );
    }
    
    // Process POST request
    const result = await processPostRequest(body, request);
    
    return NextResponse.json(result, {
      status: 201,
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
  } catch (error) {
    console.error('Edge function POST error:', error);
    
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

async function processRequest(metadata: RequestMetadata): Promise<any> {
  // Implement your edge function logic here
  return {
    message: 'Edge function executed successfully',
    metadata,
    timestamp: new Date().toISOString(),
  };
}

async function processPostRequest(body: any, request: NextRequest): Promise<any> {
  // Implement POST logic here
  return {
    message: 'POST processed successfully',
    data: body,
    timestamp: new Date().toISOString(),
  };
}

function validateRequestBody(body: any): ValidationResult {
  // Implement validation logic
  return { valid: true, errors: [] };
}

interface RequestMetadata {
  geo: {
    country: string;
    city: string;
    region: string;
  };
  ip: string;
  userAgent: string;
  referer: string;
  url: string;
}

interface ValidationResult {
  valid: boolean;
  errors: string[];
}

Specialized Edge Function Types

1. Geolocation-Based Content Delivery

// api/edge/geo-content/index.ts
import { NextRequest, NextResponse } from 'next/server';

export const runtime = 'edge';

interface ContentConfig {
  [country: string]: {
    currency: string;
    language: string;
    content: string;
    pricing: number;
  };
}

const contentConfig: ContentConfig = {
  'US': {
    currency: 'USD',
    language: 'en-US',
    content: 'Welcome to our US store!',
    pricing: 99.99,
  },
  'GB': {
    currency: 'GBP',
    language: 'en-GB',
    content: 'Welcome to our UK store!',
    pricing: 79.99,
  },
  'DE': {
    currency: 'EUR',
    language: 'de-DE',
    content: 'Willkommen in unserem deutschen Shop!',
    pricing: 89.99,
  },
};

export async function GET(request: NextRequest) {
  const country = request.geo?.country || 'US';
  const config = contentConfig[country] || contentConfig['US'];
  
  // Add region-specific headers
  const response = NextResponse.json({
    country,
    ...config,
    edgeLocation: request.geo?.region,
    timestamp: new Date().toISOString(),
  });
  
  response.headers.set('Cache-Control', 'public, s-maxage=3600, stale-while-revalidate=86400');
  response.headers.set('Vary', 'Accept-Language, CloudFront-Viewer-Country');
  response.headers.set('Content-Language', config.language);
  
  return response;
}

2. Authentication Edge Function

// api/edge/auth-check/index.ts
import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify } from 'jose';

export const runtime = 'edge';

const JWT_SECRET = new TextEncoder().encode(
  process.env.JWT_SECRET || 'your-secret-key'
);

export async function GET(request: NextRequest) {
  try {
    // Extract token from header or cookie
    const authHeader = request.headers.get('authorization');
    const cookieToken = request.cookies.get('auth-token')?.value;
    
    const token = authHeader?.replace('Bearer ', '') || cookieToken;
Read more
Ships withclaude-code-templates

Ready-to-use configurations for Anthropic's Claude Code. A comprehensive collection of AI agents, custom commands, settings, hooks, external integrations (MCPs), and project templates to enhance your development workflow.

Get the whole plugin, auto-invoked
Stats
30,156
Stars
18
Views
3,379
Forks
Active
Maintenance
Python
Language
MIT
License
2h ago
Last commit
1y ago
Created

Repo: davila7/claude-code-templates