Edge Functions allow you to run custom code at the edge of the network, closer to your users for faster response times. This guide will help you understand how to create, deploy, and manage your edge functions effectively.
Note: We are constantly evolving to make better life for developers and as of now we have limited resources. Please be patient and contact support team if something is not working.
Table of Contents
Creating a Function
Using the UI
Navigate to the Edge Functions section in your dashboard
Click the "Create Function" button
Fill in the basic information:
Function Name: Choose a unique name (4-12 characters, lowercase letters, numbers, and hyphens only)
Runtime: Select your preferred programming language and version
Write your code or upload a zip file containing your function files
Configure memory, timeout, and environment variables
Click "Deploy" to create your function
Function Naming
Names must be 4-12 characters long
Only lowercase letters, numbers, and hyphens are allowed
A random 6-character suffix will be added to your function name during deployment
Each function must have a main handler that processes incoming requests. The structure varies slightly depending on the programming language.
Node.js Example
/**
* Edge Function Handler
* @param {object} params - Parameters passed to the function
* @returns {object} Response object
*/
function main(params) {
// Log the received parameters
console.log('Received params:', params);
// Your business logic here
const result = {
message: 'Hello from Node.js!',
timestamp: new Date().toISOString(),
params: params
};
// Return the response
return {
statusCode: 200,
body: result
};
}
Python Example
import json
from datetime import datetime
def main(params):
"""
Edge Function Handler
Args:
params: Parameters passed to the function
Returns:
dict: Response object
"""
# Log the received parameters
print('Received params:', json.dumps(params))
# Your business logic here
result = {
'message': 'Hello from Python!',
'timestamp': datetime.now().isoformat(),
'params': params
}
# Return the response
return {
'statusCode': 200,
'body': result
}
Environment Variables & Parameters
Setting Environment Variables
You can set environment variables in two ways:
Through the UI: When creating or editing a function, use the Environment Variables section
During deployment: Add them to your request when using the API
Environment variables are passed to your function through the params object.
Using Parameters
Parameters are passed to your function through the params object. There are multiple ways to pass parameters:
Query parameters: These are automatically included in the params object
JSON body: For POST requests, the JSON body is merged into the params object
Environment variables: All environment variables are included in the params object
Example: Accessing Parameters
function main(params) {
// Access query parameter: /api/v1/web/org_123/default/my-function?name=John
const name = params.name;
// Access environment variable named API_KEY
const apiKey = params.API_KEY;
// Access a value from the JSON body of a POST request
const data = params.data;
return {
statusCode: 200,
body: {
message: `Hello, ${name}!`,
received: params
}
};
}
Function Limits
Our platform enforces the following limits for edge functions:
Resource
Default
Min
Max
Memory
256 MB
128 MB
1024 MB
Timeout
30 seconds
1 second
300 seconds
Package Size
-
-
10 MB
Concurrent Executions
1
-
-
Log Size
-
-
10 MB
Deploying Functions
Using the UI
Complete the function creation form
Click "Deploy" to create and activate your function
Function URL
After deployment, your function will be accessible at:
Use console.log() (Node.js) or print() (Python) to add custom log entries
Monitoring Metrics
The "Monitoring" tab provides metrics such as:
Invocation count
Error rate
Execution duration
Memory usage
Examples
Example 1: Simple API Response
function main(params) {
return {
statusCode: 200,
body: {
message: "Hello, world!",
timestamp: new Date().toISOString()
}
};
}
Example 2: Using Environment Variables for Authentication
function main(params) {
// Check for API key in parameters (from environment variables)
const apiKey = params.API_KEY;
const providedKey = params.key;
if (!apiKey || providedKey !== apiKey) {
return {
statusCode: 401,
body: {
error: "Unauthorized"
}
};
}
return {
statusCode: 200,
body: {
message: "Authentication successful",
data: {
// Your secure data here
}
}
};
}
Example 3: Processing Form Data (Node.js)
function main(params) {
// Access form fields from params
const { name, email, message } = params;
// Validate inputs
if (!name || !email || !message) {
return {
statusCode: 400,
body: {
error: "Missing required fields"
}
};
}
// Process the form data
console.log(`Form submission from ${name} (${email}): ${message}`);
// In a real scenario, you might send an email, store in a database, etc.
return {
statusCode: 200,
body: {
success: true,
message: "Form submitted successfully"
}
};
}
Example 4: Handling Different HTTP Methods
function main(params) {
// Get the HTTP method from params.__ow_method
const method = params.__ow_method || 'get';
switch (method.toLowerCase()) {
case 'get':
return handleGet(params);
case 'post':
return handlePost(params);
case 'put':
return handlePut(params);
case 'delete':
return handleDelete(params);
default:
return {
statusCode: 405,
body: {
error: "Method not allowed"
}
};
}
}
function handleGet(params) {
return {
statusCode: 200,
body: {
message: "GET request handled",
query: params
}
};
}
function handlePost(params) {
return {
statusCode: 200,
body: {
message: "POST request handled",
data: params
}
};
}
function handlePut(params) {
return {
statusCode: 200,
body: {
message: "PUT request handled",
data: params
}
};
}
function handleDelete(params) {
return {
statusCode: 200,
body: {
message: "DELETE request handled",
id: params.id
}
};
}
Example 5: External API Integration (Python)
import json
import urllib.request
from datetime import datetime
def main(params):
# Get API key from environment variables
api_key = params.get('WEATHER_API_KEY', '')
# Get location from request parameters
city = params.get('city', 'London')
# Construct API URL
url = f"https://api.example.com/weather?city={city}&apikey={api_key}"
try:
# Make API request
with urllib.request.urlopen(url) as response:
data = json.loads(response.read().decode())
# Process and return the weather data
return {
'statusCode': 200,
'body': {
'city': city,
'temperature': data.get('temp'),
'conditions': data.get('conditions'),
'timestamp': datetime.now().isoformat()
}
}
except Exception as e:
print(f"Error: {str(e)}")
return {
'statusCode': 500,
'body': {
'error': 'Failed to fetch weather data',
'message': str(e)
}
}
Example 6: Accessing OpenWhisk System Information
Your function has access to special parameters that provide information about the OpenWhisk environment: