---
title: Functions SDK Reference
description: Invoke serverless functions with the InsForge TypeScript SDK
---

## Installation

import Installation from '/snippets/sdk-installation.mdx';

<Installation />

## invoke()

Invoke a serverless function by slug.

### Parameters

- `slug` (string, required) - Function slug/name
- `body` (any, optional) - Request body (JSON-serializable)
- `headers` (object, optional) - Custom headers
- `method` ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', optional) - HTTP method (default: POST)

### Returns

```typescript
{
  data: any | null,  // Response from function
  error: Error | null
}
```

<Note>
SDK automatically includes authentication token from logged-in user.
</Note>

### Example (POST with body)

```javascript
const { data, error } = await insforge.functions.invoke('hello-world', {
  body: { name: 'World', greeting: 'Hello' }
})

console.log(data)
```

### Output (POST with body)

```json
{
  "data": {
    "message": "Hello, World!",
    "timestamp": "2024-01-15T10:30:00Z"
  },
  "error": null
}
```

### Example (GET request)

```javascript
const { data, error } = await insforge.functions.invoke('get-stats', {
  method: 'GET'
})

console.log(data)
```

### Output (GET request)

```json
{
  "data": {
    "posts": 500,
    "comments": 1200
  },
  "error": null
}
```

### Example (With custom headers)

```javascript
const { data, error } = await insforge.functions.invoke('api-endpoint', {
  method: 'PUT',
  body: { id: '123', status: 'active' },
  headers: { 'X-Custom-Header': 'value' }
})
```

### Output (With custom headers)

```json
{
  "data": {
    "updated": true,
    "id": "123"
  },
  "error": null
}
```

## Complete Serverless Function Examples

### Example 1: Public Function (No Authentication Required)

```typescript
import { createClient } from 'npm:@insforge/sdk';

export default async function(req: Request): Promise<Response> {
  const corsHeaders = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization'
  };

  if (req.method === 'OPTIONS') {
    return new Response(null, { status: 204, headers: corsHeaders });
  }

  // Create client with anon token - no authentication needed
  const client = createClient({
    baseUrl: Deno.env.get('INSFORGE_BASE_URL'),
    anonKey: Deno.env.get('ANON_KEY')
  });

  // Access public data
  const { data, error } = await client.database
    .from('public_posts')
    .select('*')
    .limit(10);

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

### Example 2: Authenticated Function (Access User Data)

```typescript
import { createClient } from 'npm:@insforge/sdk';

export default async function(req: Request): Promise<Response> {
  const corsHeaders = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization'
  };

  if (req.method === 'OPTIONS') {
    return new Response(null, { status: 204, headers: corsHeaders });
  }

  // Extract token from request headers
  const authHeader = req.headers.get('Authorization');
  const userToken = authHeader ? authHeader.replace('Bearer ', '') : null;

  // Create client with user's token for authenticated access
  const client = createClient({
    baseUrl: Deno.env.get('INSFORGE_BASE_URL'),
    edgeFunctionToken: userToken
  });

  // Get authenticated user
  const { data: userData } = await client.auth.getCurrentUser();
  if (!userData?.user?.id) {
    return new Response(JSON.stringify({ error: 'Unauthorized' }), {
      status: 401,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });
  }

  // Access user's private data or create records with user_id
  await client.database.from('user_posts').insert([{
    user_id: userData.user.id,
    content: 'My post'
  }]);

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