Lovable OpenAI integration: AI features without leaking your key
Adding AI to a Lovable app takes a prompt. Keeping the key private and the bill under control takes a few more steps. Here they are.
Keep your OpenAI key on the server, and put a limit on every user before you launch. As of 2 October 2026, Lovable gives you two ways to add AI features: its built-in Lovable AI, which needs no key from you, or your own OpenAI key stored in Secrets and called from a backend function. Either way, the browser should never see a key. The part most tutorials skip is cost: without per-user limits and a spend cap, one bad actor or one stuck loop becomes your bill.
This guide covers both routes, the safe setup for your own key, rate limits and spend caps, prompt injection, and how to test and watch it all. Platform facts are from Lovable, OpenAI, Supabase and OWASP pages checked on 2 October 2026, listed under Sources.
Should you use Lovable AI or your own OpenAI key?
Start with Lovable AI unless you have a reason not to. Lovable's documentation says its built-in AI needs no API keys or provider setup. It creates and manages a key for each project, called LOVABLE_API_KEY, and offers chat, image, video, voice and embedding models from several providers, OpenAI among them. The calls run through a backend function Lovable creates, never directly from the browser. Usage is billed in Lovable credits, and the cost depends on the model and the work done.
Your own OpenAI key makes sense when you need a model Lovable AI does not offer, or want AI usage billed to your own OpenAI account instead of your Lovable credits. Lovable's documentation says to do this by calling the provider directly from a backend edge function, with your key stored as a secret. The provider then bills that usage, and running the function still counts as regular Lovable Cloud usage. For help choosing a model, see our overview of the most advanced AI models.
| Lovable AI | Your own OpenAI key | |
|---|---|---|
| Setup | None: the key is created for you | Create a key, store it in Secrets, write a backend function |
| Billing | Lovable credits | Your OpenAI account |
| Limits you hit | Workspace rate limit in requests per minute (error 429), no credits left (error 402) | OpenAI rate and spend limits per organization and project |
| Models | Lovable's list, across providers | Any model your OpenAI account can use |
| Per-user limits | You build them | You build them |
Notice the last row. Neither route limits what one of your users can spend. That is your job either way.
Where should the OpenAI key live?
In a secret on the server, never in the frontend. Lovable's security documentation says API keys cannot be stored safely in client-side code. Anything the browser loads, a visitor can read. A key in your React code is a key anyone can copy and use on your account.
Lovable's documentation recommends three steps: store the key in Secrets, make the API call in server-side code, and call that code from the frontend. It also says Lovable detects keys pasted into the chat and guides you to Secrets instead. Still, do not type a key into a chat message. When a feature needs one, Lovable asks for it through a secure form in the chat, and you can add one yourself under More, then Cloud, then Secrets. Secrets are write-only: once saved, the value cannot be viewed again in Lovable. Our glossary entry on secrets management explains the wider practice.
Lovable's built-in backend, Cloud, is built on Supabase's open-source foundation, and Lovable's Secrets documentation shows edge functions reading values with Deno.env.get. Supabase's own documentation says a function reads a secret with Deno.env.get and the secret's name. It also warns that its secret keys, such as the service role key, bypass row-level security, so they belong in edge functions and never in a browser. OpenAI's production guide says the same about its own keys: keep them out of your code and public repositories, and use environment variables or a secret manager.
- 01Create a key for this app onlyMake a separate OpenAI project and key for this app. OpenAI's guide says you can set custom rate and spend limits per project, so this app gets its own caps, and you can revoke its key without touching anything else.
- 02Store it in SecretsAdd it in Lovable's Secrets, for example as OPENAI_API_KEY, the name Lovable's own documentation uses. Never commit it to GitHub.
- 03Call OpenAI from an edge functionThe function reads the key, calls OpenAI and returns only the answer. The browser calls your function, not OpenAI.
- 04Check who is callingThe function should require a signed-in user and read the user from the session, not from the request body.
- 05Rotate the keyOpenAI's guide recommends an expiration date on project keys and a regular rotation process. Rotate at once if the key was ever pasted anywhere public. On Lovable AI, the LOVABLE_API_KEY secret has its own Rotate action.
How do you stop one user running up your OpenAI bill?
With three layers: a limit per user, a cap on input size, and a hard spend limit at the provider. OpenAI's rate-limit guide says its limits apply at the organization and project level, not per user. So nothing at OpenAI stops one of your users from using up your whole allowance. Lovable AI is similar: its documentation says its rate limits apply per workspace.
OWASP calls this unbounded consumption, item LLM10 in its 2025 list of risks for AI applications. It describes attackers running a high volume of paid operations to put an unsustainable financial burden on the provider, which it calls denial of wallet. Its advice includes rate limits and user quotas on how many requests one source can make in a time period, strict input size limits, and logging and monitoring to catch unusual patterns of use. Our glossary entry on rate limiting explains how such limits work.
- Per-user limits: count calls per user per day in your database, and have the edge function refuse the call when the count is reached. Count before calling the model, not after.
- Input limits: cap the length of what a user can send, and cap the length of the answer you ask for.
- A cheaper fallback: when a user nears the limit, switch to a smaller model instead of failing outright.
- A provider cap: OpenAI's guide says you can set spend alerts and a hard spend limit for a monthly cap. The hard limit stops affected API traffic when tracked spend reaches it, so set it above normal use, and read OpenAI's spend-limit guide before you turn it on in production.
- An off switch: a setting that turns the AI feature off without a release, for when something goes wrong at night.
We built this kind of control for Bell, an AI email assistant its founder designed in Lovable, which is pre-launch and running on staging. In the prototype, the AI cost breakers had no callers. Now every model call goes through one router: off switch, budget, circuit breaker, then the call. Each person has a daily limit in dollars and in calls. At 80% Bell drops to cheap triage, and at 100% it stops. A global limit sits above both, and all of it can be tuned without a release. The details are in our Bell case study.
Also plan for the limits you do not control. OpenAI's guide says to follow the Retry-After header when a rate-limited response includes one: wait at least that long, plus a small random delay. Lovable's documentation says Lovable AI returns 429 when your app's requests exceed the workspace rate limit, and 402 when the workspace runs out of credits. Show the user a clear message for both, not a blank screen.
Can users trick your AI feature into leaking data?
Yes, and you cannot fully prevent it. OWASP lists prompt injection first in its 2025 risks for AI applications. It defines it as user prompts that change the model's behavior in unintended ways. Direct injection comes from what the user types. Indirect injection hides in content the model reads, such as a website or a file. OWASP says it is unclear whether fool-proof prevention exists.
So design as if the model will be fooled. The question is what happens when it is.
- Give the model only what this user may see. Fetch data with the user's own permissions, so database rules still apply.
- Never put secrets, other users' data or admin instructions in the prompt.
- Keep untrusted content apart from your instructions, and label it as data.
- Check the output before acting on it: expected format, allowed values, no surprise links.
- Require a person to approve anything irreversible, such as sending, paying or deleting.
Bell shows why. Anyone can send you an email, and an email can be written to instruct an AI. In Bell's own evaluation set, one email that wrote out its own verdict chose its own category and switched off the second check. The fix was structural: email bodies fenced off from the AI's instructions, a plain-code check before the model reads the message, and no send without a person's approval. Our article on vibe coding security risks covers the wider list.
How do you test an AI feature and watch its cost?
Test the controls, not the wording. AI answers change from run to run, so a test that checks exact text will be flaky. The limits and permissions do not change, so test those.
- A signed-out request to the function is refused.
- A user over the daily limit is refused before any model call is made.
- An oversized input is rejected.
- A prompt asking for another user's data returns nothing from that user.
- The key does not appear anywhere in the built frontend files.
Then watch it in production. Log each call with the user, the model, the tokens used and the cost, but not the full text of private prompts. Set an alert for spend above normal, and review the top users each week. Our glossary entry on observability explains what to collect. On your own key, OpenAI's spend alerts give you a second warning for the whole organization.
What does a production-ready AI feature need?
Before real users touch it, check each line below. If you cannot tick one, that is the next piece of work.
- The key is in Secrets, used only by an edge function, and rotated on a schedule.
- Every call requires a signed-in user, read from the session.
- Each user has a daily limit, checked before the model call.
- Inputs and answers have length caps.
- A provider spend limit and alerts are set.
- An off switch works without a release.
- The model sees only data the user may see, and cannot take irreversible action alone.
- Calls are logged with user, model, tokens and cost, and someone looks at them.
Starter is $2,999 a month paid annually, or $3,999 month to month; Growth is custom. See pricing, or take the free production-readiness check first: 19 questions, a score out of 100 and your three biggest risks.
Sources
Each platform fact above comes from one of these pages, checked on 2 October 2026.
- Lovable documentation: AI (docs.lovable.dev/features/ai), no keys needed, LOVABLE_API_KEY per project, calls through a backend edge function, billing in credits, workspace rate limits, errors 429 and 402, own keys from backend edge functions.
- Lovable documentation: Security (docs.lovable.dev/features/security), keys not safe in client-side code, Secrets, server-side calls, key detection in chat.
- Lovable documentation: Secrets (docs.lovable.dev/features/secrets), secure input in chat, More, Cloud, Secrets, write-only values, OPENAI_API_KEY as a backend secret, LOVABLE_API_KEY Rotate action.
- Lovable documentation: Cloud (docs.lovable.dev/integrations/cloud), the built-in backend built on Supabase's open-source foundation.
- Supabase documentation: Edge Function secrets (supabase.com/docs/guides/functions/secrets), Deno.env.get, secret keys bypass row-level security and never go in a browser.
- OpenAI: Production best practices (developers.openai.com/api/docs/guides/production-best-practices), key storage, expiry and rotation, per-project rate and spend limits, spend alerts and hard spend limit.
- OpenAI: Rate limits (developers.openai.com/api/docs/guides/rate-limits), organization and project level limits, Retry-After and backoff.
- OWASP Top 10 for LLM Applications 2025: LLM01 Prompt Injection (genai.owasp.org/llmrisk/llm01-prompt-injection).
- OWASP Top 10 for LLM Applications 2025: LLM10 Unbounded Consumption (genai.owasp.org/llmrisk/llm102025-unbounded-consumption).
- Case-study facts: our Bell case study (plutonapps.com/work/bell), as published on this site.
Common questions
Do I need my own OpenAI API key to add AI to a Lovable app?
No. Lovable's built-in AI creates and manages a key for each project and bills usage in Lovable credits. You need your own OpenAI key only if you need a model Lovable AI does not offer, or want usage billed to your own OpenAI account.
Is it safe to put my OpenAI key in a Lovable app?
Only on the server. Store the key in Lovable's Secrets and call OpenAI from a backend function. Never put it in frontend code, because anything the browser loads can be read and copied by a visitor.
How do I limit how much each user can spend on AI?
Count each user's calls in your database and have the backend function refuse calls over a daily limit, before the model is called. Add input length caps and a hard monthly spend limit at the provider as a backstop.
What do the 429 and 402 errors from Lovable AI mean?
Lovable's documentation says 429 means your app's requests exceeded the workspace rate limit, and 402 means the workspace has run out of credits. Show users a clear message for both, retry 429 after a short wait, and add credits or turn on auto top-up for 402.
Can prompt injection be fully prevented?
No. OWASP says it is unclear whether fool-proof prevention exists. Limit the damage instead: give the model only data the user may see, keep secrets out of prompts, check outputs and require a person to approve irreversible actions.
More on this: Lovable mastery & prompting
Built something in Lovable you want people to rely on?
We are the engineers who take it the rest of the way — secured, tested, released and supported.