Templates / APIs

Hide your OpenAI API key behind a proxy endpoint

A small backend endpoint that calls OpenAI for your frontend, so the API key never reaches the browser — with a per-visitor daily limit.

Calling OpenAI straight from a web or mobile app puts your secret key in every visitor’s hands. Put a tiny endpoint in between: the app calls it, it adds the key server-side, enforces a limit and returns only the reply.

Build it with Wisp

Type this into Wisp, or press Build this — it writes the code below, deploys it and gives you a URL:

A POST /chat endpoint for my frontend that takes { messages }, calls the OpenAI chat completions API with OPENAI_API_KEY and OPENAI_MODEL, returns { reply }, and allows each IP 50 requests a day.

The code

POST /chat · API

import { config, kv } from 'wisp';

const DAILY_LIMIT = 50;

export async function handler(req) {
  const messages = req.body?.messages;
  if (!Array.isArray(messages) || messages.length === 0 || messages.length > 30) {
    return { status: 400, body: { error: 'Send { messages: [{ role, content }] } with 1–30 messages' } };
  }
  // A per-visitor daily cap, so one user can't spend your whole budget.
  const day = new Date().toISOString().slice(0, 10);
  const used = await kv.incr(`chat:${req.ip}:${day}`, 1, { ttl: 86_400 });
  if (used > DAILY_LIMIT) return { status: 429, body: { error: 'Daily limit reached, try again tomorrow' } };

  const res = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: { authorization: `Bearer ${config.require('OPENAI_API_KEY')}`, 'content-type': 'application/json' },
    body: JSON.stringify({
      model: config.require('OPENAI_MODEL'),
      messages: messages.map(({ role, content }) => ({ role: role === 'assistant' ? 'assistant' : 'user', content: String(content).slice(0, 4000) })),
      max_tokens: 500,
    }),
  });
  if (!res.ok) return { status: 502, body: { error: 'The AI service failed, try again' } };
  const data = await res.json();
  return { body: { reply: data.choices[0].message.content } };
}

Set it up

Add these in the project’s Variables & secrets (secrets are encrypted and never shown in logs):

Try it

From your frontend: await fetch("https://<your-project-url>/chat", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ messages: [{ role: "user", content: "Hi" }] }) }). CORS is handled for you.

How it works

Variations

Questions

Is an environment variable in my frontend build safe? No. Anything bundled into frontend code (including VITE_ or NEXT_PUBLIC_ variables) is readable by anyone who opens the page.

Can someone still abuse my endpoint? They can call it, but only within your limits. Combine the per-IP cap with Wisp’s built-in rate limits, and require an API key or a signed-in user for anything expensive.

Build it with Wisp — free trial

Related