AI

Building your first AI feature: calling an LLM API from a web app

Avi, the Avenux Techspire mascot, illustrating: Building your first AI feature: calling an LLM API from a web app

Adding an AI feature to a website sounds like a big deal, but most of the work is plain web development. You send some text to an API, you get text back, you show it to the user. The parts that need real care are security, cost and handling failures. Let us build a small “summarise this text” feature and do it properly.

I will keep this provider-neutral. Every LLM provider has its own endpoint, request format and model names, so check their documentation for the exact details. The overall pattern is the same everywhere.

The one rule: never call the API from the browser

LLM APIs are authenticated with a secret API key, and usage is billed to your account. If you put that key in your frontend JavaScript, anyone can open the browser’s developer tools, copy it and use it on your bill. It does not matter if the code is minified or the key is in a separate file. If the browser can read it, so can everyone.

So the flow is always:

  1. The browser sends the user’s input to your server.
  2. Your server adds the secret key and calls the LLM API.
  3. Your server sends back only the result.

The key never leaves your server.

Step 1: Store the key in an environment variable

On your server, keep the key in an environment variable, not in your code. Locally, many people use a .env file:

LLM_API_KEY=your-secret-key-here
LLM_API_URL=https://api.example-llm.com/v1/generate

Add .env to .gitignore immediately, before your first commit:

echo ".env" >> .gitignore

If a key ever gets pushed to GitHub, even for a minute, treat it as leaked. Revoke it in your provider’s dashboard and create a new one.

Step 2: Write the server endpoint

Here is a small Node.js example with Express. Node 18 and later has fetch built in. The endpoint URL and request body below are placeholders; your provider’s docs will show the real shape.

import express from 'express';

const app = express();
app.use(express.json({ limit: '20kb' }));

app.post('/api/summarise', async (req, res) => {
  const text = (req.body?.text || '').trim();

  if (!text) {
    return res.status(400).json({ error: 'Text is required' });
  }
  if (text.length > 5000) {
    return res.status(400).json({ error: 'Text is too long' });
  }

  try {
    const response = await fetch(process.env.LLM_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.LLM_API_KEY}`,
      },
      body: JSON.stringify({
        instructions: 'Summarise the user text in 3 short bullet points.',
        input: text,
        max_output_tokens: 300,
      }),
      signal: AbortSignal.timeout(30000),
    });

    if (!response.ok) {
      console.error('LLM API error', response.status);
      return res.status(502).json({ error: 'AI service unavailable' });
    }

    const data = await response.json();
    // Adjust this to match your provider's response format
    res.json({ summary: data.output_text });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Something went wrong' });
  }
});

app.listen(3000);

Load the .env file however you prefer. Recent Node versions support node --env-file=.env server.js, or you can use the dotenv package. In production, set the variables in your hosting panel or your systemd service file instead.

Some things worth pointing out:

  • Input limits. We cap the request size and text length. LLM usage is usually billed by how much text goes in and comes out, so unlimited input means unlimited cost.
  • Output limits. Most APIs let you cap the length of the response. Use it.
  • Timeouts. LLM calls can take several seconds. Do not let a request hang forever.
  • Generic errors to the user. Log the details on the server, but do not send raw API errors to the browser. They can contain information you do not want to expose.

Step 3: Call your endpoint from the frontend

The browser code knows nothing about the LLM provider. It only talks to your own API:

async function summarise() {
  const text = document.querySelector('#input').value;
  const output = document.querySelector('#output');
  output.textContent = 'Working on it...';

  try {
    const res = await fetch('/api/summarise', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text }),
    });
    const data = await res.json();
    output.textContent = res.ok ? data.summary : data.error;
  } catch {
    output.textContent = 'Network error, please try again.';
  }
}

Notice we use textContent, not innerHTML. Treat AI output like any other untrusted input. If you insert it as HTML, you open yourself to script injection.

Step 4: Protect the endpoint

Your /api/summarise route is now a public door to a paid service. Before going live:

  • Add rate limiting per IP or per user, so one person or bot cannot run up your bill. For Express, express-rate-limit is a common choice.
  • Require login if the feature is only meant for your users.
  • Set a spending limit or alert in your provider’s dashboard if they offer one.
  • Use a separate key per project or environment, so you can revoke one without breaking everything.

Step 5: Expect imperfect answers

LLMs can produce wrong or odd output. Design for it:

  • Keep instructions clear and specific in your request.
  • If you need structured data, ask for JSON and validate it on the server with try/catch around JSON.parse before using it.
  • Show users that the content is AI-generated where that matters, and let them edit or retry.
  • Do not send sensitive personal data to a third-party API unless you have checked the provider’s data policy and have the user’s consent.

Going further

Once the basic version works, you can look at streaming responses so text appears word by word, caching results for repeated inputs, and keeping a short conversation history for chat-style features. All of these build on the same base: your server in the middle, the key in an environment variable, and limits on everything.

That is the real lesson here. The AI part is one API call. The engineering is everything around it.