After this lesson, you will be able to: Add a real AI feature to one of your apps by calling the Anthropic or OpenAI API from a backend route, safely, and with a good UX.
Now that you've used AI tools, you can build with them, adding AI features to apps you ship. This lesson walks through calling the Anthropic API from your Express backend, streaming responses, handling errors, and the security mistakes to avoid.
If you call the Anthropic or OpenAI API from frontend JavaScript, anyone who opens DevTools sees your key, and can spend your money. All AI API calls must go through your backend. Your frontend talks to your backend, your backend talks to the API.
Install: npm install @anthropic-ai/sdk. Set ANTHROPIC_API_KEY in your environment.
// server.jsconst express = require("express");const Anthropic = require("@anthropic-ai/sdk").default;const app = express();app.use(express.json());const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });app.post("/api/ask", async (req, res) => {const { question } = req.body;if (!question || question.length > 2000) {return res.status(400).json({ error: "invalid question" });}const response = await anthropic.messages.create({model: "claude-sonnet-4-6",max_tokens: 1024,messages: [{ role: "user", content: question }],});res.json({ answer: response.content[0].text });});app.listen(3000);
Standard fetch, the secret stays on the server.
// In your frontend script.jsasync function ask(question) {const res = await fetch("/api/ask", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ question }),});const data = await res.json();document.querySelector("#answer").textContent = data.answer;}
Pick the smallest model that does the job. For a chatbot or content generator, Claude Haiku or GPT-4o-mini is fast and cheap. For coding help or complex reasoning, Claude Sonnet or GPT-4o. Save the biggest models (Opus, GPT-4) for the moments where the answer quality really matters.
Build a tiny app that lets users ask AI a question and shows the answer.
In the in-browser editor, create a Node.js project with Express
Add ANTHROPIC_API_KEY to the in-browser editor Secrets
Write the POST /api/ask route from above
Build a tiny HTML page with an input, a button, and a result div
Wire the frontend to call /api/ask and render the answer
Deploy the project and share the URL
Hint: think about who can see your network requests.
Sign in and purchase access to unlock this lesson.