Prerequisites
- Ensure you have a Microsoft Azure account and a subscription with Cognitive Services enabled.
- Have a Netlify account with a site already set up to deploy.
- Basic understanding of HTML, JavaScript, and serverless functions.
Set Up Azure Cognitive Services
- Go to the Azure portal and log in with your credentials.
- Navigate to Cognitive Services and create a new resource. Choose the API you need such as Text Analytics, Computer Vision, etc.
- Once created, retrieve your endpoint and API key from the resource overview page.
Create a Function in Netlify
- In your Netlify project directory, create a new folder named
functions
.
- Create a new file within
functions
, e.g., processText.js
if using Text Analytics. This will be your serverless function.
Write the Serverless Function
const fetch = require('node-fetch');
exports.handler = async function(event, context) {
// Ensure it is a POST request
if (event.httpMethod !== 'POST') return { statusCode: 405, body: 'Method Not Allowed' };
const { text } = JSON.parse(event.body);
const apiEndpoint = 'https://your-cognitive-service-endpoint/text/analytics/v3.0/sentiment';
const apiKey = 'YOUR_API_KEY';
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({ documents: [{ id: '1', text }] })
});
const data = await response.json();
return {
statusCode: 200,
body: JSON.stringify(data)
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: 'Error processing request' })
};
}
}
Deploy to Netlify
- Ensure that your
netlify.toml
file is set correctly to include functions from your functions
directory:
[build]
functions = "functions"
- Push your changes to your repository. Netlify will automatically deploy your changes including the serverless function.
Test Your Integration
- Deployed serverless functions are accessible via
/.netlify/functions/functionName
. For example, if your function is named processText
, use /.netlify/functions/processText
.
- Use a tool like Postman to send a POST request to your endpoint with JSON body data containing the text to be analyzed.
- Check to see that the response contains the expected output from Azure Cognitive Services.
Handle Environment Variables
- It's not safe to hardcode your API key. Instead, go to your Netlify dashboard and navigate to Site settings > Build & deploy > Environment > Environment variables.
- Add a new variable with the key set as
AZURE_API_KEY
and the value as your actual API key.
- Update your function to use the environment variable:
const apiKey = process.env.AZURE_API_KEY;
Optimize and Secure Your Integration
- Implement error handling and logging in your function to capture any issues.
- Consider rate limiting and authentication if you are exposing this function to the public to prevent misuse.