Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/InsForge/InsForge/llms.txt

Use this file to discover all available pages before exploring further.

Overview

InsForge Functions provide serverless compute powered by Deno. Write custom backend logic in TypeScript/JavaScript without managing servers.

Key Features

  • Deno Runtime - Modern, secure JavaScript/TypeScript execution
  • Single Endpoint - One function = one endpoint
  • All HTTP Methods - GET, POST, PUT, PATCH, DELETE support
  • Request/Response API - Standard Web API (Request/Response objects)
  • Instant Deployment - Deploy via API or dashboard
  • Auto-scaling - Scales automatically with demand

Architecture

Creating Functions

Basic Function

// Export default async function
export default async function(request: Request): Promise<Response> {
  const { name = 'World' } = await request.json();
  
  return new Response(
    JSON.stringify({ message: `Hello, ${name}!` }),
    {
      headers: { 'Content-Type': 'application/json' },
      status: 200
    }
  );
}

Function Signature

All functions must export a default async function:
export default async function(
  request: Request
): Promise<Response> {
  // Your code here
  return new Response(...);
}

Request Handling

Reading Request Data

export default async function(request: Request) {
  const data = await request.json();
  console.log('Received:', data);
  
  return new Response(
    JSON.stringify({ received: data }),
    { headers: { 'Content-Type': 'application/json' } }
  );
}

Returning Responses

return new Response(
  JSON.stringify({ success: true, data: result }),
  {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  }
);

Invoking Functions

Via SDK

import { createClient } from '@insforge/sdk';

const client = createClient({
  baseUrl: 'https://your-app.region.insforge.app',
  anonKey: 'your-anon-key'
});

const { data, error } = await client.functions.invoke('hello-world', {
  body: { name: 'John' }
});

if (error) {
  console.error('Function error:', error);
} else {
  console.log('Result:', data);
}

Direct HTTP Calls

curl https://your-app.region.insforge.app/functions/hello-world

Use Cases

Webhook Handler

export default async function(request: Request) {
  // Validate webhook signature
  const signature = request.headers.get('X-Webhook-Signature');
  
  // Parse webhook payload
  const payload = await request.json();
  
  // Process event
  if (payload.event === 'order.created') {
    // Send confirmation email
    // Update analytics
    // Notify admin
  }
  
  return new Response(
    JSON.stringify({ received: true }),
    { status: 200, headers: { 'Content-Type': 'application/json' } }
  );
}

Data Processing

export default async function(request: Request) {
  const { items } = await request.json();
  
  // Process data
  const processed = items.map((item: any) => ({
    ...item,
    processed: true,
    timestamp: new Date().toISOString()
  }));
  
  // Could also save to database here
  // await client.database.from('processed_items').insert(processed);
  
  return new Response(
    JSON.stringify({ processed }),
    { headers: { 'Content-Type': 'application/json' } }
  );
}

API Proxy

export default async function(request: Request) {
  const url = new URL(request.url);
  const endpoint = url.searchParams.get('endpoint');
  
  // Call external API
  const response = await fetch(`https://api.example.com/${endpoint}`, {
    headers: {
      'Authorization': `Bearer ${Deno.env.get('EXTERNAL_API_KEY')}`
    }
  });
  
  const data = await response.json();
  
  return new Response(
    JSON.stringify(data),
    { headers: { 'Content-Type': 'application/json' } }
  );
}

Email Sender

export default async function(request: Request) {
  const { to, subject, html } = await request.json();
  
  // Send email via external service
  const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${Deno.env.get('SENDGRID_API_KEY')}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      personalizations: [{ to: [{ email: to }] }],
      from: { email: 'noreply@yourapp.com' },
      subject,
      content: [{ type: 'text/html', value: html }]
    })
  });
  
  return new Response(
    JSON.stringify({ sent: response.ok }),
    { status: response.ok ? 200 : 500,
      headers: { 'Content-Type': 'application/json' }
    }
  );
}

Function Management

List Functions

curl https://your-app.region.insforge.app/api/functions \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
Response:
[
  {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "slug": "hello-world",
    "name": "Hello World Function",
    "description": "Returns a greeting message",
    "status": "active",
    "created_at": "2024-01-21T10:30:00Z",
    "updated_at": "2024-01-21T10:35:00Z",
    "deployed_at": "2024-01-21T10:35:00Z"
  }
]

Get Function Details

curl https://your-app.region.insforge.app/api/functions/hello-world \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"

Update Function

curl -X PUT https://your-app.region.insforge.app/api/functions/hello-world \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "export default async function(request) { ... }",
    "status": "active"
  }'

Delete Function

curl -X DELETE https://your-app.region.insforge.app/api/functions/hello-world \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"

Function Status

StatusDescription
draftNot deployed, not callable
activeDeployed and callable
errorDeployment failed

Deno Runtime

Available APIs

Deno provides modern web standards:
  • Fetch API - HTTP requests
  • URL API - URL parsing
  • FormData - Form data handling
  • ReadableStream - Streaming
  • Crypto API - Cryptography
  • Web Storage API - localStorage/sessionStorage

Environment Variables

const apiKey = Deno.env.get('EXTERNAL_API_KEY');
const dbUrl = Deno.env.get('DATABASE_URL');
Contact support to set environment variables for your functions.

Security

Dangerous operations are blocked:
  • Deno.run() - Process execution
  • Deno.spawn() - Process spawning
  • File system access (restricted)

Limitations

Important Constraints
  • No Subpaths - One function = one endpoint (no /function/path/subpath)
  • No WebSockets - Use Real-time API for WebSocket connections
  • Execution Time - Functions timeout after 30 seconds
  • Memory - Limited to 512MB per execution

Error Handling

export default async function(request: Request) {
  try {
    const data = await request.json();
    const result = await processData(data);
    
    return new Response(
      JSON.stringify({ success: true, result }),
      { headers: { 'Content-Type': 'application/json' } }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({ 
        error: error.message,
        stack: error.stack 
      }),
      { 
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      }
    );
  }
}

API Reference

Management Endpoints (Admin)

GET    /api/functions              # List all functions
POST   /api/functions              # Create function
GET    /api/functions/{slug}       # Get function details
PUT    /api/functions/{slug}       # Update function
DELETE /api/functions/{slug}       # Delete function

Execution Endpoint (Client)

* /functions/{slug}  # Execute function (all HTTP methods)

Function Metadata

interface FunctionMetadata {
  id: string;
  slug: string;
  name: string;
  description?: string;
  status: 'draft' | 'active' | 'error';
  created_at: string;
  updated_at: string;
  deployed_at?: string;
}

interface FunctionDetails extends FunctionMetadata {
  code: string;
}

Best Practices

Keep Functions Small

Each function should do one thing well

Use Environment Variables

Store API keys and secrets in environment variables, not code

Return Proper Status Codes

Use HTTP status codes correctly (200, 400, 404, 500, etc.)

Handle Errors Gracefully

Always catch and return meaningful error messages

Validate Input

Check request data before processing

Next Steps

Database

Query database from functions

Storage

Process uploaded files

AI Integration

Add AI capabilities to functions

Real-time

Trigger real-time events