Deploy a nodejs function

This guide walks you through deploying, testing, monitoring, and managing a Node.js function on PandaEdge.

Prerequisites

  • A PandaEdge account

  • Basic knowledge of JavaScript/Node.js

  • Your function code ready for deployment

  • Appropriate access role (Owner or Admin for deployment)

Supported Node.js Versions

  • Node.js 14

  • Node.js 16

  • Node.js 18 (Default)

  • Node.js 20

Deployment Steps

1. Create a New Function

  1. Navigate to the Edge Functions dashboard

  2. Click "Create New" button

  3. Select "Node.js" as your runtime

  4. Choose your preferred Node.js version

2. Function Naming

Ensure your function name is:

  • 4-12 characters long

  • Contains only lowercase letters, numbers, and hyphens

  • Unique within your organization

3. Write Your Function

Basic function template:

/**
 * 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
    };
}

4. Configure Function

{
    "name": "my-function",    // 4-12 characters, lowercase letters, numbers, hyphens
    "runtime": "nodejs:18",   // Your selected Node.js version
    "memory": 256,           // Memory allocation in MB (128-1024)
    "timeout": 30            // Timeout in seconds (1-300)
}

5. Manage Dependencies

Create package.json:

{
    "name": "my-function",
    "version": "1.0.0",
    "dependencies": {
        "axios": "^0.24.0",
        "moment": "^2.29.1"
    }
}

Version Management

1. Version History

  • View all deployed versions

  • See deployment timestamps

  • Track authors and changes

  • Compare version performance

2. Rollback Capability

  • Roll back to any previous version

  • Instant version switching

  • No downtime during rollback

  • Automatic version tracking

Testing Features

1. Basic Testing

Use the built-in test interface to:

  • Send test requests

  • View responses

  • Check execution time

  • Monitor memory usage

2. Test Cases

Create reusable test cases:

// Test case configuration
{
    "name": "User Creation Test",
    "path": "/api/users",
    "method": "post",
    "params": {
        "name": "John Doe",
        "email": "[email protected]"
    },
    "expectedResult": {
        "statusCode": 200,
        "body": {
            "success": true
        }
    }
}

3. Debugging

  1. Set breakpoints in your code

  2. Inspect variables during execution

  3. View call stack

  4. Step through code execution

4. Mock Data Generation

Generate test data for:

  • Strings

  • Numbers

  • Booleans

  • Arrays

  • Objects

Function Examples

1. HTTP Request Handler

const axios = require('axios');

async function main(params) {
    try {
        const response = await axios.get('https://api.example.com/data', {
            headers: {
                'Authorization': `Bearer ${process.env.API_TOKEN}`
            }
        });

        return {
            statusCode: 200,
            body: response.data
        };
    } catch (error) {
        console.error('API request failed:', error);
        return {
            statusCode: error.response?.status || 500,
            body: {
                error: error.message
            }
        };
    }
}

2. Version-Aware Function

function main(params) {
    // Get function version from environment
    const version = process.env.FUNCTION_VERSION || '1.0.0';
    
    console.log(`Executing function version: ${version}`);
    
    try {
        // Version-specific logic
        const result = version.startsWith('2') 
            ? handleV2Request(params)
            : handleV1Request(params);
            
        return {
            statusCode: 200,
            body: {
                version: version,
                result: result
            }
        };
    } catch (error) {
        console.error(`Error in version ${version}:`, error);
        return {
            statusCode: 500,
            body: {
                error: error.message,
                version: version
            }
        };
    }
}

Best Practices

1. Version Control

  • Tag versions meaningfully

  • Document changes

  • Test before rollback

  • Monitor version performance

  • Keep deployment history

2. Error Handling

function main(params) {
    try {
        // Your code here
    } catch (error) {
        console.error('Function failed:', error);
        return {
            statusCode: 500,
            body: {
                error: error.message,
                version: process.env.FUNCTION_VERSION
            }
        };
    }
}

3. Resource Management

  • Use appropriate memory allocation

  • Set reasonable timeouts

  • Clean up resources

  • Handle connections properly

4. Security

  • Validate input data

  • Sanitize output

  • Use environment variables for secrets

  • Implement proper authentication

Troubleshooting

1. Common Issues

  1. Memory Issues

    • Monitor memory usage

    • Optimize data structures

    • Clean up resources

    • Increase memory allocation if needed

  2. Version Issues

    • Check version history

    • Verify deployment logs

    • Test previous versions

    • Monitor version metrics

  3. Dependency Issues

    • Verify package versions

    • Check compatibility

    • Update dependencies

    • Review package size

Last updated