Priya wants a button in the office at Shree Vidya Tuition Centre: type a student name and a fee balance, click “Draft reminder,” and get a short, polite message for the parent. That is the same job as the PHP cURL lesson, but this time the staff would use a page in the browser.
JavaScript can send that request — from Node.js on a server, or from a script in the page. The second option is the trap. If you put the API key in front-end JavaScript, anyone who opens View source, the browser’s network panel, or a saved copy of the page can take the key and bill your account. This lesson shows how to call an OpenAI-compatible chat-completions endpoint with fetch from Node.js, how to give the page a small /api/reminder endpoint, and how to keep AI_API_KEY in the server environment, never in the browser. We will not hardcode a key, and we will not let the model invent the rupee amount.
Key takeaways
- A chat call is a POST of JSON to
/v1/chat/completions. The assistant text is usually atchoices[0].message.content. - Node.js may read
AI_API_KEYfrom the environment, the same way PHP and Python do. - Never put the API key in a script tag, a front-end bundle, or a public repository.
- A page in the browser should POST facts to your own server; that server holds the key and calls the model.
- Put official names and amounts into the prompt from your own data, and put the reply into the page with
textContent, notinnerHTML.
What you are calling
A typical request is an HTTP POST to {base url}/v1/chat/completions. The body is JSON:
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You write short, polite messages for a tuition centre in India. Use rupees when mentioning fees. Do not invent amounts."
},
{
"role": "user",
"content": "Write a 2-sentence reminder that Ananya Sharma has a balance of ₹1,200 for November tuition."
}
],
"max_tokens": 200
}
The system message sets the tone. The user message holds the task and the facts. Put the rupee amount in that user text yourself. If you only say “remind them about the pending fee,” the model may guess a number, which is not acceptable for money.
A successful response includes a choices array. The text you want is usually here:
choices[0].message.content
The same JSON shape works from PHP, Python, Node.js, or a browser. What changes is where the key lives.
Why the key must not go in the browser
Front-end JavaScript is public. A const apiKey = "sk-…" in a <script> tag, in a bundled .js file, or in a header you send from the page to https://api.openai.com will show up in the downloaded source. A parent, a student on the office Wi‑Fi, or a search engine cache could use it.
The safe split is:
- The browser may collect the student name, the balance, and the month, then
fetch('/api/reminder')on your site. It never sees the provider key. - Your server (Node.js in this lesson, or PHP if you followed the cURL lesson) reads
AI_API_KEYfrom the environment, calls the model, and returns only the message text.
If you only need a script you run in a terminal, skip the page and call the API from Node.js directly — that is still server-side code, and the key stays in the environment.
Keep the API key in the Node.js environment
On the server, the request is authorized with a header:
Authorization: Bearer YOUR_KEY_HERE
The key is a secret. It is not a string you type into a file and commit, and it is not a value the browser may send you. Read it from the environment instead.
function apiKeyFromEnv(name = 'AI_API_KEY', env = process.env) {
const key = env[name];
if (typeof key !== 'string' || key === '') {
throw new Error(
`Missing API key. Set the ${name} environment variable. Do not hardcode the key, and never put it in front-end JavaScript.`
);
}
return key;
}
In a terminal you can export the variable before you run the script:
export AI_API_KEY="paste-the-key-here"
node reminder.mjs
On a server, set it in the hosting panel, in a systemd unit, or in a file outside the web root that your process manager loads. Never print the key, never put it in HTML, and never send it back to the browser. You can also read the base URL from the environment, with a sensible default, so the same script can point at OpenAI, a compatible proxy, or a local mock while you practise:
const baseUrl = process.env.AI_API_BASE || 'https://api.openai.com';
const model = process.env.AI_MODEL || 'gpt-4o-mini';
Build the JSON and send it with fetch
Modern Node.js (18 and later) has a built-in fetch, the same function a browser uses. The difference is that this code runs on the server, where process.env is available and the key is not shipped to the visitor.
function buildChatRequest(model, messages, maxTokens = 200) {
const body = { model, messages };
if (maxTokens !== null) {
body.max_tokens = maxTokens;
}
return body;
}
function reminderMessages(student, balance, month) {
const amount = Number(balance);
if (!student || typeof student !== 'string') {
throw new Error('A student name is required.');
}
if (!Number.isFinite(amount) || amount < 0) {
throw new Error('A numeric balance in rupees is required.');
}
const formatted = amount.toLocaleString('en-IN');
return [
{
role: 'system',
content: 'You write short, polite messages for a tuition centre in India. Use rupees when mentioning fees. Do not invent amounts or dates.',
},
{
role: 'user',
content: `Write a 2-sentence reminder that ${student} has a balance of ₹${formatted} for ${month} tuition.`,
},
];
}
async function callChatCompletions(baseUrl, apiKey, payload, timeoutSeconds = 20) {
const url = `${String(baseUrl).replace(/\/$/, '')}/v1/chat/completions`;
let response;
try {
response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(timeoutSeconds * 1000),
});
} catch (err) {
if (err && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
throw new Error('Request timed out.');
}
throw new Error('Network error: ' + (err && err.message ? err.message : String(err)));
}
const responseBody = await response.text();
let decoded;
try {
decoded = JSON.parse(responseBody);
} catch {
throw new Error('The API did not return valid JSON. HTTP ' + response.status);
}
if (!response.ok) {
const message = (decoded.error && decoded.error.message) || ('HTTP ' + response.status);
throw new Error('API error: ' + message);
}
const text = decoded.choices && decoded.choices[0] && decoded.choices[0].message
? decoded.choices[0].message.content
: null;
if (typeof text !== 'string' || text === '') {
throw new Error('The API response had no message content.');
}
return {
status: response.status,
content: text,
raw: decoded,
};
}
A few choices in that function are deliberate. AbortSignal.timeout stops a hung call from blocking your process; twenty seconds is a starting point, not a rule. Reading response.text() first, then JSON.parse, lets you treat a non-JSON body as its own failure. JSON.stringify keeps the rupee sign readable in the request body.
Error handling comes in layers, and you should keep them separate:
- The network itself failed (DNS, timeout, TLS):
fetchrejects. The API never produced a body you can trust. - The server answered, but not with JSON:
JSON.parsethrows. Log the HTTP status and a short snippet of the body, not the key. - JSON arrived with a 4xx or 5xx status: many providers put a human message in
error.message(for example an invalid key). Surface a short, safe message to the page; keep the detail in the server log. - A 200 response with an empty
choices[0].message.content: treat it as a failure so you do not show a parent a blank note.
Put it together for a fee reminder
async function draftFeeReminder(input, env = process.env) {
const apiKey = apiKeyFromEnv('AI_API_KEY', env);
const baseUrl = env.AI_API_BASE || 'https://api.openai.com';
const model = env.AI_MODEL || 'gpt-4o-mini';
const payload = buildChatRequest(
model,
reminderMessages(input.student, input.balance, input.month)
);
return callChatCompletions(baseUrl, apiKey, payload);
}
const result = await draftFeeReminder({
student: 'Ananya Sharma',
balance: 1200, // rupees; this value comes from your register, not from the model
month: 'November',
});
console.log(result.content);
The rupee figure is formatted in JavaScript with toLocaleString('en-IN'), then placed in the prompt. If this script later feeds a web page, assign the model’s text with textContent. A model is not a trusted source, even when you sent it the facts.
Let a web page call your server, not the provider
The page should post only the facts. The handler below takes student, balance, and month from the body. If a client also sends an apiKey field, it is ignored. The JSON you return contains only content — never the environment key.
async function handleReminderRequest(body, env = process.env) {
const result = await draftFeeReminder(
{ student: body.student, balance: body.balance, month: body.month },
env
);
return { content: result.content };
}
A tiny Node.js HTTP server can expose that as POST /api/reminder. On a failure, send a short message to the browser and write the real error to the server log:
import http from 'node:http';
async function readJsonBody(req) {
const chunks = [];
for await (const chunk of req) {
chunks.push(chunk);
}
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}
const server = http.createServer(async (req, res) => {
if (req.method === 'POST' && req.url === '/api/reminder') {
try {
const body = await readJsonBody(req);
const result = await handleReminderRequest(body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} catch (err) {
res.writeHead(err.statusCode || 502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Could not write the reminder just now. Please try again or send it by hand.' }));
console.error('AI reminder failed:', err.message);
}
return;
}
res.writeHead(404);
res.end();
});
server.listen(3000, '127.0.0.1');
The page itself has no key and does not call the model provider:
<p id="reminder-out"></p>
<form id="reminder-form">
<button type="submit">Draft reminder</button>
</form>
<script>
document.getElementById('reminder-form').addEventListener('submit', async function (event) {
event.preventDefault();
const out = document.getElementById('reminder-out');
out.textContent = 'Writing the reminder…';
try {
const response = await fetch('/api/reminder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
student: 'Ananya Sharma',
balance: 1200,
month: 'November'
})
});
const data = await response.json();
if (!response.ok || !data.content) {
out.textContent = 'Could not write the reminder just now. Please try again or send it by hand.';
return;
}
out.textContent = data.content;
} catch (err) {
out.textContent = 'Could not write the reminder just now. Please try again or send it by hand.';
}
});
</script>
Notice that the browser posts to /api/reminder on your own origin, not to api.openai.com. The reply is written with textContent, so a stray HTML tag in the model’s text cannot change the page.
Try this
First run the Node.js script without setting AI_API_KEY. You should get the missing-key error, not a request to the network. Then set a fake key and point AI_API_BASE at a local mock, or at a real compatible endpoint if you already have an account. Change the input so the balance is ₹2,450 and the student is Rahul Iyer. Confirm that the reply mentions ₹2,450 and does not invent a different amount. If you add the small server, open the page’s network panel and confirm that the key does not appear in the request or the response.
How this was tested
On Node.js 24, the request builder produced valid JSON, an empty AI_API_KEY raised the missing-key error, and a sample success body parsed to the reminder text. The fetch call was then pointed at a local mock of POST /v1/chat/completions: a matching Bearer token returned HTTP 200 and a ₹1,200 message; a wrong token returned HTTP 401 and the function threw API error: Invalid API key. A local POST /api/reminder returned only the message text, ignored an apiKey field sent in the body, and never included the environment key in the JSON. No paid API was called here, so run one live call against your own provider before you rely on it.
What you learned
- An OpenAI-compatible chat call is a POST of JSON to
/v1/chat/completions, withmodeland amessageslist. - Node.js can send that call with built-in
fetchand readAI_API_KEYfrom the environment. - The API key must not appear in front-end JavaScript, in a public file, or in the JSON you send back to the browser.
- A page should post facts to your own
/api/reminder(or to the PHP endpoint from the cURL lesson); the server calls the model. - Put official amounts and names into the prompt from your own data, and assign the model’s text with
textContent.
Quick quiz
-
1. Where should the API key be stored when you use JavaScript?
- A) In a
<script>tag on the page, sofetchcan send it to the provider - B) In an environment variable on the server (Node.js), never in front-end code
- C) In a public GitHub repository named
secrets, so every machine can share it
Show answer
B. Front-end JavaScript is public. A key in a script tag, a bundle, or a git history can be copied and billed against. Use
AI_API_KEYon the server. - A) In a
-
2. A page in the tuition office should draft a reminder. How should the browser get the text?
- A)
fetch('https://api.openai.com/v1/chat/completions')with the Bearer token in the page - B)
fetch('/api/reminder')on your own server, which holds the key and calls the model - C) Save the key in
localStorage, then call the provider
Show answer
B. The browser may send facts to your origin. Your server reads the environment key and returns only the message text.
- A)
-
3. After a 200 JSON response, where is the assistant text usually found?
- A)
choices[0].message.content - B) The
Authorizationheader - C)
error.message
Show answer
A. Treat a missing or empty content string as a failure so you do not show a blank reminder. The Authorization header must never be sent back to the page.
- A)
-
4. How should you put the model’s reply into the page?
- A)
out.innerHTML = data.content - B)
out.textContent = data.content - C)
document.write(data.content)
Show answer
B. A model is not a trusted source.
textContentinserts the words as text, so a tag in the reply cannot change the page. - A)
Related lessons
- Call an AI API from PHP with cURL — the same chat call, with the key held in PHP.
- Your First AI Program in Python: Send a Prompt and Read the Reply — the same idea in Python with the
requestslibrary. - Prompt Engineering for Developers: Clear Instructions, Examples and JSON Output — tighter instructions, and JSON your server can validate before you use it.