Technology Encyclopedia Home >Edge Functions 101: How to Deploy Serverless Code at 3,200+ Global Edge Nodes

Edge Functions 101: How to Deploy Serverless Code at 3,200+ Global Edge Nodes

Summary: Edge functions let you run serverless code at 3,200+ global edge nodes—milliseconds from your users. From A/B testing to personalization to API gateways, edge functions unlock use cases impossible with traditional cloud architecture. This beginner's guide covers everything from concept to deployment.


Tencent Cloud EdgeOne Product Introduction

What if you could run code everywhere, instantly?

Traditional cloud architecture has a fundamental limitation: your code runs in a few data centers, far from most of your users. Edge functions solve this by running your code at 3,200+ locations worldwide—within milliseconds of every user on Earth.

Real-world use cases:

  • A/B testing without client-side JavaScript
  • Personalized content without origin round-trips
  • API gateway logic at the edge
  • Authentication and authorization at the edge
  • URL rewriting and redirects
  • Header manipulation and security headers
  • Real-time data transformation

The result: Sub-50ms response times globally, reduced origin load by 70-90%, and entirely new application architectures.

Let's explore what edge functions are, how they work, and how to deploy your first edge function.

What Are Edge Functions?

Definition

Edge functions are lightweight, serverless code snippets that execute at CDN edge nodes—as close to your users as possible.

Key Properties:

  • Serverless: No servers to manage
  • Global: Runs at 3,200+ locations
  • Fast: Sub-50ms cold start, sub-10ms warm start
  • Scalable: Handles millions of requests per second
  • Secure: Sandboxed execution environment

How Edge Functions Work

User Request → Edge Node → Edge Function Executes → Response
                              ↓ (optional)
                         Origin Server

Execution Flow:

  1. User request arrives at nearest edge node
  2. Edge function code executes locally
  3. Function can: modify request, generate response, fetch from origin, call APIs
  4. Response sent to user from edge (sub-50ms)

Edge Functions vs Traditional Serverless

Feature Edge Functions Traditional Serverless (Lambda)
Locations 3,200+ edge nodes 20-30 regions
Cold Start < 50ms 100-1000ms
Warm Start < 10ms 10-50ms
Proximity to User < 100 miles 500-5,000 miles
Max Execution 50ms-30s (varies) Up to 15 minutes
Languages JavaScript/TypeScript Multiple
Use Cases Request/response manipulation General-purpose compute

Top 10 Edge Function Use Cases

1. A/B Testing Without Client-Side Code

The Problem: Client-side A/B testing causes page flicker, requires JavaScript, and is easily detected.

Edge Function Solution:

// A/B test at the edge - no client-side code needed
export default {
  async fetch(request) {
    const variant = Math.random() < 0.5 ? 'A' : 'B';
    const url = new URL(request.url);
    url.pathname = `/variants/${variant}${url.pathname}`;
    const response = await fetch(url.toString());
    const newResponse = new Response(response.body, response);
    newResponse.headers.set('X-Variant', variant);
    return newResponse;
  }
};

Benefits: No page flicker, faster loading, not detectable by bots.

2. Geolocation-Based Content

The Problem: Showing different content by country requires origin logic and database lookups.

Edge Function Solution:

export default {
  async fetch(request) {
    const country = request.headers.get('CF-IPCountry') || 'US';
    const currency = { 'US': 'USD', 'GB': 'GBP', 'JP': 'JPY', 'DE': 'EUR' }[country] || 'USD';
    
    const response = await fetch(request);
    let html = await response.text();
    html = html.replace('{{CURRENCY}}', currency);
    html = html.replace('{{COUNTRY}}', country);
    
    return new Response(html, { headers: response.headers });
  }
};

Benefits: Sub-10ms personalization, no origin load, accurate geolocation.

3. Authentication at the Edge

The Problem: Every API request travels to origin for authentication, adding 100-300ms latency.

Edge Function Solution:

export default {
  async fetch(request) {
    const token = request.headers.get('Authorization')?.replace('Bearer ', '');
    if (!token) return new Response('Unauthorized', { status: 401 });
    
    // Verify JWT at edge (no origin round-trip)
    const isValid = await verifyJWT(token, JWT_SECRET);
    if (!isValid) return new Response('Invalid token', { status: 403 });
    
    // Forward authenticated request to origin
    return fetch(request);
  }
};

Benefits: Authentication in < 10ms (vs 100-300ms at origin), reduced origin load.

4. Smart Redirects and URL Rewriting

Redirect rules, vanity URLs, and URL normalization—all at the edge.

5. Security Headers

Add Content-Security-Policy, X-Frame-Options, HSTS, and other security headers without origin changes.

6. API Rate Limiting

Implement per-user, per-endpoint rate limiting at the edge with sub-millisecond overhead.

7. Image Optimization

Resize, compress, and convert images on-the-fly at the edge based on device type and connection speed.

8. Bot Detection and Challenge

Custom bot detection logic at the edge—fingerprinting, challenge/response, behavioral analysis.

9. Cache Key Customization

Generate custom cache keys based on headers, cookies, or query parameters for more efficient caching.

10. Real-Time Data Transformation

Transform API responses at the edge—filter fields, aggregate data, format for different clients.

Getting Started: Deploy Your First Edge Function

Step 1: Set Up Your Development Environment

Prerequisites:

  • Edge platform account
  • Node.js 16+ installed
  • Platform CLI tool installed

Step 2: Create Your Function

// my-first-edge-function.js
export default {
  async fetch(request) {
    // Get request information
    const url = new URL(request.url);
    const path = url.pathname;
    const country = request.headers.get('CF-IPCountry') || 'Unknown';
    
    // Custom logic at the edge
    if (path === '/api/hello') {
      return new Response(JSON.stringify({
        message: 'Hello from the edge!',
        country: country,
        timestamp: new Date().toISOString(),
        edgeLocation: request.headers.get('CF-Ray') || 'Unknown'
      }), {
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Pass through to origin for other paths
    return fetch(request);
  }
};

Step 3: Test Locally

# Test your function locally
npx edge-dev my-first-edge-function.js

# Visit http://localhost:8787/api/hello

Step 4: Deploy to Edge

# Deploy to all 3,200+ edge nodes
npx edge-deploy my-first-edge-function.js --production

# Your function is now running at 3,200+ locations worldwide!

Step 5: Verify Deployment

# Test from multiple regions
curl https://your-domain.com/api/hello -H "Host: your-domain.com"

# Response:
# {
#   "message": "Hello from the edge!",
#   "country": "US",
#   "timestamp": "2026-03-27T12:00:00.000Z",
#   "edgeLocation": "LAX-1234"
# }

Performance Comparison

Edge Function vs Origin Computation

Metric Origin (US-East) Edge Function Improvement
US Users 80ms 10ms -88%
EU Users 180ms 15ms -92%
Asia Users 280ms 12ms -96%
Brazil Users 220ms 18ms -92%
Australia Users 300ms 14ms -95%
Global Average 212ms 14ms -93%

Real-World Performance

Case Study: Ecommerce A/B Testing

Before (Client-side A/B):

  • Page load time: 2.8 seconds (JavaScript-based testing)
  • Page flicker: Visible to users
  • Bot detection: Easy to detect and bypass

After (Edge Function A/B):

  • Page load time: 0.9 seconds (-68%)
  • Page flicker: None (server-side)
  • Bot detection: Not detectable

Revenue Impact: +15% conversion rate (from faster page loads + no flicker)

Key Features for Edge Functions

When choosing an edge function platform, ensure it includes:

3,200+ Global Edge Nodes

  • Code runs everywhere
  • Sub-50ms cold start
  • Sub-10ms warm start

JavaScript/TypeScript Support

  • Standard Web APIs
  • Fetch API for origin/API calls
  • Crypto API for encryption

Environment Variables

  • Store secrets securely
  • Per-environment configuration
  • No hardcoded credentials

Edge KV Storage

  • Key-value storage at edge
  • Sub-millisecond reads
  • Global consistency

Real-Time Logging

  • Tail logs in real-time
  • Error tracking and debugging
  • Performance metrics

CI/CD Integration

  • GitHub Actions
  • GitLab CI
  • Terraform support

Common Mistakes to Avoid

Mistake 1: Running Heavy Computation at Edge

Edge functions have execution time limits (typically 50ms-30s). Heavy computation belongs at origin.

Mistake 2: Making Too Many Origin Calls

Each origin call adds latency. Cache responses and minimize origin round-trips.

Mistake 3: Not Using Edge KV for Configuration

Don't hardcode configuration. Use edge KV storage for dynamic configuration that can be updated without redeployment.

Mistake 4: Ignoring Cold Start Performance

First request after idle has higher latency (cold start). Optimize function initialization code.

Mistake 5: Not Testing from Multiple Regions

Edge functions behave differently in different regions. Test from multiple locations.

The ROI of Edge Functions

Performance:

  • Response time: -90%+ (vs origin computation)
  • Page load time: -40-70%
  • Conversion rate: +10-20%

Cost:

  • Origin server load: -70-90%
  • Serverless compute cost: -50-80%
  • Development time: -30-50% (simpler architecture)

Take Action Today

Edge functions unlock new application architectures that are impossible with traditional cloud. Start with a simple use case and expand from there.

Get Started in 3 Steps:

  1. Identify Use Case — A/B testing, geo-routing, authentication, or API gateway
  2. Write Your Function — Simple JavaScript/TypeScript
  3. Deploy Globally — One command deploys to 3,200+ locations

Pricing Plans with Edge Functions

Plan Best For Specifications Original Price Promo Price
Free Personal Developers, MVP Teams Basic protection & static acceleration —— $0/month
Personal Early-Stage Businesses 50GB + 3M requests | CDN + Security $4.2/month $0.9/month
Basic Growing Businesses 500GB + 20M requests | OWASP TOP 10 $57/month $32/month
Standard Enterprise Businesses 3TB + 50M requests | WAF + Bot Management $590/month $299/month

Deploy Edge Functions Today

Get Started with Tencent Cloud EdgeOne

View Current Promotions & Discounts


Run code everywhere. Edge functions deploy to 3,200+ locations in seconds. Try it free today and build the next generation of applications.