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 atnetlify/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
Create the Function File
Create a TypeScript file at
netlify/functions/chat.ts:netlify/functions/chat.ts
Configure Environment Variables
Add your Azure AI API token to Netlify:
- Go to your Netlify site dashboard
- Navigate to Site settings > Environment variables
- Add a new variable:
- Key:
API_TOKEN - Value: Your Azure AI API token
- Key:
Function Endpoint
Once deployed, your function is accessible at: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:Making Requests
Call the function from your frontend:Error Handling
The function provides detailed error responses:Error details including stack traces are logged for debugging. Consider removing sensitive information in production.
Local Development
Test your function locally using Netlify CLI:http://localhost:8888/.netlify/functions/chat
Best Practices
- Environment Variables: Never commit API tokens to version control
- Error Logging: Use
console.logfor 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:- Go to Functions tab
- Select your function
- View real-time logs and invocation history