Skip to main content

Overview

This portfolio uses Netlify Functions to create a serverless backend that proxies requests to Azure AI services. The serverless function handles CORS, authentication, and API communication without requiring a dedicated backend server.

Function Architecture

The chat function is located at netlify/functions/chat.ts and serves as a proxy between your frontend and Azure AI’s chat completion API.

Key Features

  • CORS Support: Automatically handles preflight requests and cross-origin communication
  • Secure API Key Management: Uses environment variables to protect your Azure AI API token
  • Error Handling: Comprehensive error logging and user-friendly error responses
  • Zero Configuration Deployment: Automatically deployed with your Netlify site

Implementation

1

Create the Function File

Create a TypeScript file at netlify/functions/chat.ts:
netlify/functions/chat.ts
import { Handler } from '@netlify/functions';

export const handler: Handler = async (event) => {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    'Access-Control-Allow-Methods': 'POST, OPTIONS',
    'Content-Type': 'application/json'
  };

  // Handle preflight requests
  if (event.httpMethod === 'OPTIONS') {
    return {
      statusCode: 200,
      headers
    };
  }

  try {
    if (!event.body) {
      throw new Error('No request body');
    }

    const response = await fetch('https://models.inference.ai.azure.com/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.API_TOKEN}`
      },
      body: event.body
    });

    const data = await response.json();

    return {
      statusCode: 200,
      headers,
      body: JSON.stringify(data)
    };
  } catch (error) {
    console.error('Error:', error);
    return {
      statusCode: 500,
      headers,
      body: JSON.stringify({ 
        error: error instanceof Error ? error.message : 'Unknown error occurred',
        details: error instanceof Error ? error.stack : undefined
      })
    };
  }
};
2

Configure Environment Variables

Add your Azure AI API token to Netlify:
  1. Go to your Netlify site dashboard
  2. Navigate to Site settings > Environment variables
  3. Add a new variable:
    • Key: API_TOKEN
    • Value: Your Azure AI API token
3

Deploy

Netlify automatically detects and deploys functions in the netlify/functions/ directory. No additional configuration needed!

Function Endpoint

Once deployed, your function is accessible at:
https://your-site.netlify.app/.netlify/functions/chat
Netlify automatically creates an endpoint for each function file. The endpoint name matches the filename.

CORS Configuration

The function includes comprehensive CORS headers to allow cross-origin requests:
const headers = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization',
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
  'Content-Type': 'application/json'
};
The current configuration allows requests from any origin (*). For production, consider restricting this to your specific domain.

Making Requests

Call the function from your frontend:
const response = await fetch('/.netlify/functions/chat', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    messages: [
      { role: 'user', content: 'Hello!' }
    ],
    model: 'gpt-4o-mini',
    max_tokens: 1000
  })
});

const data = await response.json();

Error Handling

The function provides detailed error responses:
{
  error: "Error message",
  details: "Stack trace (in development)"
}
Error details including stack traces are logged for debugging. Consider removing sensitive information in production.

Local Development

Test your function locally using Netlify CLI:
# Install Netlify CLI
npm install -g netlify-cli

# Run locally
netlify dev
Your function will be available at http://localhost:8888/.netlify/functions/chat

Best Practices

  • Environment Variables: Never commit API tokens to version control
  • Error Logging: Use console.log for debugging; logs are visible in Netlify’s function logs
  • Timeout Handling: Netlify functions have a 10-second timeout on free plans
  • Cold Starts: First request may be slower; consider implementing warming strategies

Monitoring

View function logs and performance metrics in your Netlify dashboard:
  1. Go to Functions tab
  2. Select your function
  3. View real-time logs and invocation history

Build docs developers (and LLMs) love