In this guide12 sections
Lovable can connect an app to almost any HTTP API, but the correct architecture depends on one question: does the request require a secret, privileged credential, or user-specific authorization? If it does, the browser must not call the provider with that credential directly.
A secure integration usually has three parts. The Lovable frontend collects input and displays states. A server-side Edge Function validates the user and request, reads secrets, and calls the provider. The provider response is reduced to the data the browser actually needs. This boundary protects credentials and gives you one place to enforce permissions, timeouts, retries, logging, and spend controls.
This guide explains the whole path, including the parts that quick tutorials skip: CORS, rate limits, OAuth token ownership, webhook verification, duplicate events, response contracts, failure UX, and the difference between runtime APIs and Lovable's build-time connectors.
First identify which kind of Lovable integration you need
The phrase connect an API is used for several different jobs in Lovable. Confusing them leads to the wrong setup. A runtime API integration becomes part of the published application. An app connector also adds functionality to deployed apps through a supported shared connection. A chat connector, often based on MCP, gives the Lovable Agent context or tools while you build but is not shipped as a capability inside the customer-facing app.
There is also a separate Lovable API, sometimes described as Build with URL. That API creates and shares Lovable projects programmatically. It is not the mechanism for making your finished app call a weather, CRM, shipping, AI, or accounting service.
Lovable's integration documentation (opens in a new tab) explicitly separates app connectors, chat connectors, and API integrations. Write the intended actor and moment before you configure anything: the published app calls the service for an end user, or the Lovable Agent uses a tool during development.
| Integration | Who uses it | When it runs |
|---|---|---|
| Runtime API | Your published application | When a user or backend workflow needs external data or an action |
| App connector | Your published application | At runtime through a supported shared service connection |
| Chat connector or MCP | Lovable Agent | During project creation and editing only |
| Lovable API / Build with URL | An external workflow creating Lovable projects | When another system starts a new Lovable build |
Note
This article is about runtime API integrations. An MCP connection that helps Lovable read documentation during a build does not automatically give your published users that API feature.
Decide whether the API can be called from the browser
A genuinely public endpoint with no credential and no privileged operation can often be called directly from the frontend. Examples include an open public dataset or a service explicitly designed for anonymous browser requests. Even then, review CORS, rate limits, response size, uptime, privacy, and whether the provider permits direct client use.
An authenticated API should normally be called from a server-side function. This includes API keys, bearer tokens, basic credentials, private certificates, signing secrets, service-account credentials, and any operation that creates, changes, or deletes provider data. Lovable's documented path is to enable Lovable Cloud, store the credential as a secret, and use an Edge Function for the provider request.
Some values are public by design, such as a publishable client identifier. Public does not mean unlimited or harmless. Pair the provider's documentation with a threat review. A value that can authorize spending, read private records, or act as your business must never be embedded in generated browser code.
| Request type | Recommended path | Reason |
|---|---|---|
| No credentials, anonymous read-only data | Direct browser request if CORS and terms allow | No secret to protect, simplest path |
| Shared API key or bearer token | Edge Function plus secret storage | Prevents credential exposure |
| User-specific OAuth | Server callback, protected token storage and Edge Function | Tokens belong to a user and require lifecycle management |
| Privileged write or billable action | Authenticated Edge Function with authorization and limits | Requires identity, validation, auditability and abuse controls |
| Incoming webhook | Public server endpoint with signature verification | Provider initiates the request and authenticity must be checked |
Watch out
Never paste a private API key into a prompt, component, browser environment variable, network request, screenshot, or Git repository. Add it through the platform's secret manager only when the project is ready to use it.
Turn the provider documentation into an API contract
Lovable produces better integration code when the request is specified precisely. Give it the base URL, endpoint path, HTTP method, authentication method, required headers, request body, query parameters, success response, error responses, rate-limit behavior, and the provider's official documentation link. An OpenAPI specification is especially useful when it is current and scoped to the endpoints you need.
Do not ask for a whole platform integration when the feature only needs two endpoints. Start with the narrowest useful operation and model a stable internal response. Provider payloads are often large and inconsistent. Your Edge Function can translate them into a smaller application contract so UI code does not become coupled to every field and naming choice in the external service.
Define what null, missing, delayed, duplicated, and partial data mean. A successful HTTP status does not always mean the business action succeeded, and some APIs return errors inside a nominally successful response. Record the provider's identifiers because they are essential for reconciliation and support.
- Base URL, version and exact endpoint paths.
- HTTP method and content type.
- Authentication location: header, query parameter, signed body, OAuth or another mechanism.
- Required and optional request fields with validation rules.
- Representative success, empty, validation, unauthorized, rate-limit and server-error responses.
- Provider timeout guidance, idempotency support and retry headers.
- Stable internal response fields the Lovable frontend will use.
- Provider terms governing storage, caching, display, privacy and redistribution.
Use an Edge Function as the security and reliability boundary
The Edge Function should do more than hide a key. It should authenticate the caller where needed, authorize the requested action, validate and normalize input, add the provider credential, enforce a timeout, classify errors, and return a deliberately limited response. For expensive or sensitive operations, it should also rate-limit users and record a safe audit event.
Never accept authority from the browser. If the request contains a customer ID, organization ID, plan, price, email recipient, or file location, confirm that the signed-in user may act on it. Load authoritative values from the database when manipulation would create financial, privacy, or security risk.
Separate provider errors from user-facing copy. Logs can retain a request identifier, provider status, duration, endpoint category, and safe diagnostic message. The browser should receive a stable error code and a useful next action without stack traces, credentials, raw provider bodies, or personal data it does not need.
Browser
-> sends validated intent and user session
Edge Function
-> verifies session and permission
-> validates input and loads authoritative records
-> reads provider key from Secrets
-> calls provider with timeout and request ID
-> normalizes response or error
-> records safe operational metadata
Browser
<- receives only the fields needed for the interfaceTip
Ask Lovable to show which code runs in the browser and which runs in the Edge Function. Then inspect the browser network request. No secret should appear in the JavaScript bundle, request headers, query string, or response.
Handle CORS, timeouts and network failure deliberately
CORS is a browser rule that controls whether JavaScript from one origin may read a response from another. If a public API does not allow your storefront domain, changing frontend headers cannot force permission. Call the service through an Edge Function you control, or use the provider's supported browser SDK and origin configuration.
Every external request can be slow or unavailable. Set a finite timeout and design the interface for loading, empty, delayed, retryable, and terminal failure states. A button should not remain in a permanent spinner. Preserve user input when a safe retry is possible, and prevent double submission while the first request is unresolved.
Retry only operations that are safe to repeat or protected by an idempotency key. Repeating a read is usually less dangerous than repeating a charge, booking, message, or record creation. Honor provider retry guidance and Retry-After headers. Use backoff rather than an immediate loop that amplifies an outage and consumes the account's quota.
| Failure | Application behavior | Operator evidence |
|---|---|---|
| Timeout | Explain delay and offer a controlled retry | Duration, endpoint and request ID |
| 401 or 403 | Ask for reconnection or deny the action | Credential or permission category without logging the secret |
| 429 rate limit | Pause, show when retry is possible, avoid automatic loops | Quota headers and affected account |
| Provider 5xx | Fail gracefully and retry only when safe | Provider status, request ID and attempt count |
| Invalid response | Do not render untrusted assumptions | Schema-validation error and redacted sample |
Plan user-specific OAuth as a product feature
OAuth is required when each user connects their own account at another service. It is not equivalent to storing one shared API key. The application sends the user to the provider, receives an authorization callback, exchanges a short-lived code for tokens on the server, stores those tokens against the correct user or organization, and refreshes or revokes them over time.
Register exact production and preview callback URLs with the provider. Include a state value that binds the callback to the initiating session and protects against request forgery. If the provider supports PKCE, use the documented flow. Request the minimum scopes needed, explain them before redirecting, and give users a visible disconnect action.
Store access and refresh tokens in protected server-side storage. Do not return them to the frontend or place them in a general profile row. Encrypt where the platform and risk model require it, restrict which functions can read them, and delete or revoke them when a connection is removed. Handle revoked consent and refresh failure as normal states rather than unexplained server errors.
- Exact callback URLs for every allowed environment.
- State validation and PKCE where supported.
- Minimum requested scopes with a clear user explanation.
- Protected mapping from provider account to application user or organization.
- Secure token refresh, expiry, revocation and disconnect behavior.
- Reauthorization UX when the provider invalidates the connection.
Watch out
Do not implement OAuth by asking users to paste long-lived personal tokens into a form unless the provider explicitly requires that model and the application has a safe server-side storage and deletion process.
Verify webhooks and make events idempotent
A webhook reverses the direction of the request: the provider calls your application when something changes. The endpoint is public by necessity, so authentication usually relies on a provider signature or secret. Verify the signature against the raw request exactly as the provider documents before parsing or trusting the event.
Return the provider's expected success status quickly. If processing is expensive, record the verified event and continue asynchronously where the platform permits. Providers retry when delivery fails, which means the same event can arrive more than once or out of order. Store the provider event ID and make processing idempotent.
Do not trust a redirect back to the browser as proof that a payment, import, or remote job completed. The webhook or a server-to-server status check should update authoritative state. Reconcile records periodically for workflows where missing an event affects access, revenue, or customer data.
- 1
Create a dedicated endpoint
Use HTTPS and keep the route focused on one provider or event family.
- 2
Preserve the raw body
Many signature schemes require the exact received bytes rather than re-serialized JSON.
- 3
Verify authenticity first
Reject invalid signatures, timestamps outside the allowed window, and unsupported event types.
- 4
Deduplicate
Store the provider event ID and make a repeated delivery return success without repeating the business action.
- 5
Process safely
Load authoritative records, apply the state transition once, and record enough metadata for reconciliation.
- 6
Monitor failures
Alert on repeated delivery errors and provide a controlled replay process.
Control rate limits, cost and abuse
Hiding an API key protects the credential from direct theft, but it does not stop users from making expensive requests through your own function. Tie quotas to the authenticated user or organization, validate payload size, limit concurrency, and cap provider usage according to the product plan.
Cache safe, non-personal responses when provider terms allow it. Debounce type-ahead searches and cancel stale requests. Avoid calling an AI, search, geocoding, or data API on every render. For billable generation, make the cost-triggering action explicit and prevent accidental double submission.
Set alerts and provider-side spend limits where available. Track successful calls, failures, latency, rate limiting, and estimated usage by feature. An integration can be technically correct and still be commercially unsafe if one loop or abusive account can consume the monthly allowance in minutes.
- Per-user, per-organization and global request limits.
- Input length, file size, allowed content type and concurrency limits.
- Caching rules that respect freshness, privacy and provider terms.
- Timeouts and bounded retries with idempotency where needed.
- Usage alerts, provider budgets and an emergency disable switch.
- A product response for quota exceeded that explains the next available action.
Test the integration beyond one successful response
Use a provider sandbox or non-production account when available. Build fixtures for success, empty results, invalid input, expired credentials, insufficient scope, rate limits, timeouts, malformed responses, provider errors, and duplicate webhook events. Test with a user who is not allowed to perform the action.
Observability should answer four questions: which feature failed, for which safe internal account reference, at what provider stage, and whether retrying is safe. Correlate browser, Edge Function, and provider logs with a request ID. Redact authorization headers, tokens, request bodies containing secrets, and sensitive response fields.
After launch, monitor business outcomes as well as technical status. A 200 response is not useful if imported records are incomplete, checkout state is stale, or the user never sees the result. Add a product-level success event and compare it with provider calls so silent integration failures become visible.
| Test | Why it matters | Pass condition |
|---|---|---|
| Secret exposure | Generated code can accidentally move credentials client-side | No private value in bundle, browser request, URL or response |
| Unauthorized user | UI controls can be bypassed | Edge Function rejects before provider action |
| Timeout and retry | Networks and providers fail | Bounded, understandable behavior without duplicate action |
| Rate limit | Quota is finite | App respects retry timing and does not loop |
| Schema change | Provider responses evolve | Validation catches incompatible data safely |
| Duplicate webhook | Providers retry events | Business transition occurs once |
| Provider outage | External uptime is not yours | Core app degrades gracefully and operators are alerted |
A reusable prompt for connecting an API to Lovable
Give Lovable the smallest complete contract. Replace the bracketed concepts with real documentation, but add the secret through Cloud settings rather than pasting its value into the prompt.
Integrate the provider API as a runtime feature in this published app. This is not an MCP or chat connector.
Endpoint: GET https://api.example.com/v1/resources
Authentication: Bearer token stored only in Cloud Secrets as PROVIDER_API_KEY. Never expose it in frontend code, environment output, URLs, logs or responses.
Create an Edge Function that verifies the Lovable user session, validates the query, enforces a 10-second timeout and a per-user rate limit, calls the provider, and returns only id, name, status and updatedAt.
Handle: loading, empty result, invalid input, 401/403, 429 with Retry-After, timeout, malformed response and provider 5xx. Do not retry writes unless the provider supports idempotency.
Add a request ID across the frontend and Edge Function logs. Redact authorization headers and personal data.
Before implementing, show the browser-to-function-to-provider data flow, the secret boundary, request and response schemas, error mapping, rate-limit plan and acceptance tests.Tip
Follow the implementation with a focused review: inspect generated files, search for the secret name and value, test direct unauthorized requests, and verify every error state. Our Lovable security checklist covers the wider application boundary.
Key takeaways
- Public, credential-free APIs may be called from the browser when CORS and provider terms allow it.
- Authenticated and privileged API calls belong in Edge Functions with secrets stored server-side.
- Runtime APIs, app connectors, MCP chat connectors, and the Lovable API solve different problems.
- An Edge Function should enforce identity, permission, validation, timeout, error mapping, and safe logging, not only hide a key.
- OAuth needs server-side callbacks and token lifecycle management; webhooks need signature verification and deduplication.
- Test unauthorized access, rate limits, timeouts, schema changes, duplicate events, provider outages, and cost controls before launch.
Frequently asked questions
Lovable documents support for public and private external APIs. Public credential-free endpoints can often be called directly, while authenticated APIs use Lovable Cloud secrets and an Edge Function. Actual compatibility still depends on the provider's protocol, terms, network access, and authentication model.


