← Level 5 – Inventor

Lesson 6 of 8 ⏱ 40 minutes Premium

AI on the server

Build a server endpoint that talks to AI, and hides your secret key from the world.

Why we don’t call AI directly from the browser

AI services (OpenAI, Anthropic, and others) require an API key: a secret code that identifies you and is used for billing. And here’s the catch:

Anything you put into JavaScript in the browser can be read by anyone (F12 → source code). If your key were there, anyone could call the AI using your money.

You already know the solution from Master: your own server. The key stays on the server, and the browser only talks to your server:

Browser  →  your server (the key is here!)  →  AI service
Browser  ←  your server                     ←  AI service

Show me: the /ask endpoint

We’ll build on the Express server from Master. We’ll store the key in a .env file (this never goes on GitHub: add it to .gitignore!):

AI_KLIC=sk-your-secret-key-here

And the server gets a new endpoint:

require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.static('public'));

app.post('/ask', async (req, res) => {
  const { question } = req.body;

  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${process.env.AI_KLIC}`,
    },
    body: JSON.stringify({
      model: 'gpt-4o-mini',
      messages: [
        { role: 'system', content: 'You are a friendly helper. Answer briefly in English.' },
        { role: 'user', content: question },
      ],
    }),
  });

  const data = await response.json();
  res.json({ text: data.choices[0].message.content });
});

app.listen(3000, () => console.log('Server running at http://localhost:3000'));

What’s new here:

💡

Where do I get a key? AI services issue API keys after registration, and it’s usually paid (though cheap, just cents per answer). This is a job for a parent: ask them to create a key for you and add a small amount of credit (a few dollars is enough). Without a key, you can still test with a made-up response: see “Your turn” below.

Your turn 💪

  1. Add a line .env to .gitignore: check it with the git status command (the .env file must not show up).
  2. Create the /ask endpoint following the example.
  3. Don’t have a key? No problem, just return a test response for now and continue to the next lesson:
app.post('/ask', (req, res) => {
  res.json({ text: `Test answer to: "${req.body.question}"` });
});
  1. Try the endpoint from the browser (F12 console):
const r = await fetch('/ask', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ question: 'Hi, who are you?' }),
});
console.log(await r.json());
✅

Check: The server responds to POST /ask (with a test or real AI answer), and the secret key is neither in the code nor on GitHub.

What to take away from this lesson