Set Up OpenAI API Key
- Sign up or log in to your OpenAI account to access your API key. An API key is essential for authenticating your requests.
- Navigate to the API keys section in the OpenAI dashboard and create a new secret key if you haven't done so already.
- Copy the secret key to use in your application — keep it secure and avoid sharing it publicly.
Create a Netlify Site
- If you don't have a Netlify account, sign up at Netlify.com. Log in if you already have an account.
- Start a new site by dragging and dropping your static website folder or connect your repository from GitHub, Bitbucket, or GitLab.
- Follow the setup instructions to deploy your site and get your site up and running on a Netlify subdomain.
Environment Variables Configuration
- Open your Netlify site dashboard and find the "Site settings".
- Go to "Build & deploy" and then to "Environment". Scroll down to find "Environment variables".
- Add a new environment variable with the key name e.g.,
OPENAI_API_KEY
and paste your OpenAI secret key as the value.
Set Up Frontend to Make Requests
- In your frontend code, you'll need to set up a method to make HTTP requests to the OpenAI API using the key stored in Netlify's environment.
- Use JavaScript's
fetch
API or a library like axios
to perform AJAX requests. Ensure you do not expose your API key in client-side code.
// Example with axios
import axios from 'axios';
const fetchAIResponse = async (input) => {
try {
const response = await axios.post('/.netlify/functions/fetch-openai', { input });
return response.data;
} catch (error) {
console.error('Error fetching data from OpenAI', error);
}
};
Create a Serverless Function on Netlify
- Set up a serverless function on Netlify to securely use your OpenAI API key. Create a new folder named
functions
in your project directory.
- Create a new JavaScript file within the
functions
folder, for example, fetch-openai.js
.
- Implement the serverless function to make secure server-side API requests to OpenAI.
// Example serverless function in fetch-openai.js
exports.handler = async (event, context) => {
const { input } = JSON.parse(event.body);
const openAIKey = process.env.OPENAI_API_KEY;
try {
const response = await fetch("https://api.openai.com/v1/engines/davinci-codex/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${openAIKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
prompt: input,
max_tokens: 100
})
});
const data = await response.json();
return {
statusCode: 200,
body: JSON.stringify(data)
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: 'Failed to fetch from OpenAI API' })
};
}
};
Deploy and Test Your Site
- Push your changes to the repository linked with Netlify, or use the drag-and-drop method in the Netlify dashboard to deploy.
- Visit your Netlify site to test and confirm that requests from the frontend properly invoke the serverless function and return data from OpenAI's API.
- Use browser console or observation tools in the Netlify dashboard to monitor for any errors during the test and adjust your code if necessary.