Day 02 of 07
Connect Claude to your website safely
Goal: Today you build the hidden middleman, a Netlify Function that sits between your website and Claude. Your API key stays on Netlify and never appears in your website code.
What to do
Open your project in GitHub Desktop
Open GitHub Desktop. Select your website repository from the left sidebar. Click Fetch origin to pull any recent changes. Then open your project folder in your file manager. You should see the files from your 5-day challenge.
Create the netlify/functions/ folder
In your project folder, create a new folder called netlify. Inside that folder, create another folder called functions. The path should be your-project/netlify/functions/. You can do this in Windows Explorer or Mac Finder by right-clicking and selecting New Folder.
Create the chat.js file
Inside the functions folder, create a new file called chat.js. Open it in any text editor. Paste the complete code below and do not change anything:
const Anthropic = require('@anthropic-ai/sdk')
exports.handler = async (event) => {
if (event.httpMethod !== 'POST') {
return { statusCode: 405, body: 'Method not allowed' }
}
try {
const { message } = JSON.parse(event.body)
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY })
const response = await client.messages.create({
model: 'claude-haiku-4-5-20251001',
max_tokens: 300,
messages: [{ role: 'user', content: message }],
})
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({ reply: response.content[0].text }),
}
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({ error: 'Something went wrong. Please try again.' }),
}
}
}Create a package.json for the function
Inside the same netlify/functions/ folder, create a second file called package.json. Paste this content exactly:
{
"dependencies": {
"@anthropic-ai/sdk": "^0.36.0"
}
}Add your API key to Netlify environment variables
Log in to app.netlify.com. Click your website. Go to Site configuration then Environment variables then Add a variable. Set the variable name to ANTHROPIC_API_KEY and paste your API key as the value. Click Save.
Commit, push, and confirm the deploy succeeds
In GitHub Desktop, you should see two new files: netlify/functions/chat.js and netlify/functions/package.json. Commit message: Add Claude chatbot function. Commit to main, then push origin. Watch your Netlify dashboard and wait for the green Published status.
Expected result
Your Netlify site has a working function at /.netlify/functions/chat. Your API key is stored safely in Netlify environment variables and does not appear in any code file.
Key takeaway
- The Netlify Function is your security layer. Your API key lives on Netlify, not in your website code.