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):
OPENAI_API_KEY— platform.openai.com → API keys. Stored as a secret, never sent to the browser.OPENAI_MODEL— The model to use, as a variable — change it without touching code.
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
- The browser only ever sees your endpoint’s URL; the key stays in the function’s secrets.
- Only
userandassistantroles are accepted, so visitors can’t inject a system prompt; each message is capped at 4,000 characters. kv.incris atomic, so the daily counter is correct even under concurrent requests; the key expires after a day.
Variations
- Add a fixed system prompt server-side for your product’s persona.
- Require a signed-in user (check your auth provider’s JWT) instead of limiting by IP.
- Stream the response with server-sent events for a typing effect.
- Swap in Anthropic’s Messages API — only the URL, headers and response shape change.
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