> For the complete documentation index, see [llms.txt](https://docs.pandastack.io/v1/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pandastack.io/v1/getting-started/pandaedge.md).

# PandaEdge

## Edge Functions User Guide

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.

### Table of Contents

1. [Creating a Function](#creating-a-function)
2. [Supported Runtimes](#supported-runtimes)
3. [Function Structure](#function-structure)
4. [Environment Variables & Parameters](#environment-variables-and-parameters)
5. [Function Limits](#function-limits)
6. [Deploying Functions](#deploying-functions)
7. [Testing Functions](#testing-functions)
8. [Monitoring & Logs](#monitoring-and-logs)
9. [Examples](#examples)
10. [Troubleshooting](#troubleshooting)

### Creating a Function

#### Using the UI

1. Navigate to the Edge Functions section in your dashboard
2. Click the "Create Function" button
3. 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
4. Write your code or upload a zip file containing your function files
5. Configure memory, timeout, and environment variables
6. 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

### Supported Runtimes

Our platform supports multiple programming languages:

| Runtime   | Versions       | Main File    |
| --------- | -------------- | ------------ |
| Node.js   | 14, 16, 18, 20 | `index.js`   |
| Python    | 3, 3.9         | `main.py`    |
| Java      | 8              | `Main.java`  |
| Swift     | 5.1            | `main.swift` |
| PHP       | 7.4            | `index.php`  |
| Ruby      | 2.5            | `main.rb`    |
| Go        | 1.15           | `main.go`    |
| Rust      | 1.54           | `main.rs`    |
| .NET      | 3.1            | `Main.cs`    |
| Ballerina | 0.990          | `main.bal`   |

### Function Structure

Each function must have a `main` handler that processes incoming requests. The structure varies slightly depending on the programming language.

#### Node.js Example

```javascript
/**
 * 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

```python
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:

1. **Through the UI**: When creating or editing a function, use the Environment Variables section
2. **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:

1. **Query parameters**: These are automatically included in the `params` object
2. **JSON body**: For POST requests, the JSON body is merged into the `params` object
3. **Environment variables**: All environment variables are included in the `params` object

#### Example: Accessing Parameters

```javascript
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

1. Complete the function creation form
2. Click "Deploy" to create and activate your function

#### Function URL

After deployment, your function will be accessible at:

```
https://edge.pandastack.app/api/v1/web/org_{ORG_ID}/default/{FUNCTION_NAME}
```

### Testing Functions

#### Using the UI

1. Navigate to your function's details page
2. Go to the "Testing" tab
3. Enter test parameters in JSON format
4. Click "Test Function" to see the result

#### Using cURL

You can test your function using cURL:

```bash
curl -X POST "https://edge.pandastack.app/api/v1/web/org_{ORG_ID}/default/{FUNCTION_NAME}" \
  -H "Content-Type: application/json" \
  -d '{"key": "value"}'
```

### Monitoring & Logs

#### Viewing Logs

1. Navigate to your function's details page
2. Go to the "Logs" tab to see execution logs
3. 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

```javascript
function main(params) {
    return {
        statusCode: 200,
        body: {
            message: "Hello, world!",
            timestamp: new Date().toISOString()
        }
    };
}
```

#### Example 2: Using Environment Variables for Authentication

```javascript
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)

```javascript
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

```javascript
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)

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

```javascript
function main(params) {
    // OpenWhisk system parameters
    const systemInfo = {
        activationId: params.__OW_ACTIVATION_ID,
        actionName: params.__OW_ACTION_NAME,
        namespace: params.__OW_NAMESPACE,
        apiHost: params.__OW_API_HOST,
        deadline: params.__OW_DEADLINE
    };
    
    return {
        statusCode: 200,
        body: {
            message: "OpenWhisk System Information",
            system: systemInfo
        }
    };
}
```

### Troubleshooting

#### Common Issues

1. **Function Returns 502 Bad Gateway**
   * Ensure your function returns a proper response object
   * Check your function logs for errors
   * Verify your function isn't timing out
2. **Environment Variables Not Working**
   * Make sure they are correctly set in the UI
   * Verify you're accessing them via the `params` object
3. **Function Takes Too Long to Execute**
   * Check if your function is making slow external API calls
   * Consider increasing the memory allocation
   * Optimize your code for better performance

#### Getting Help

If you continue to experience issues, please contact our support team with:

* Your function name
* Any error messages
* Steps to reproduce the issue
* Relevant logs

***

For more information or technical support, please contact our support team at <mark style="color:purple;"><support@pandastack.io></mark>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.pandastack.io/v1/getting-started/pandaedge.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
