An app built with Lovable, Bolt, Cursor or Claude Code usually works well on its own. It starts to break when it has to talk to real systems: an accounting system like Tripletex, a CRM like Pipedrive, payments in Stripe, a Shopify store or a marketplace like FINN. This guide explains what goes wrong in those integrations and how to fix it yourself, with small code examples you can hand to your AI tool.
It is written for founders and small teams who build with AI and want their integration to survive production. It is written by Rocksoft, a software company with teams in Poland and Norwegian-speaking staff, building integrations and custom software for companies in Norway and across Europe.
Why does an integration break when the app worked fine?
Because a demo only tests the happy path. In production, other systems behave in ways your app never saw while you were building it:
- Access tokens expire, and the app has no way to refresh them.
- The same webhook arrives twice, and the app creates two invoices.
- The API returns 50 records per page, and the app only ever reads the first page.
- The other system throttles you with HTTP 429, and the sync silently stops halfway.
- A key that was fine in testing is now in the browser bundle, where anyone can read it.
AI coding tools are good at writing the call that works. They are less reliable at the code around it: what happens when the call fails, runs twice or runs out of order. The rest of this guide is about that code.
OAuth, API keys or session tokens: which one should my app use?
You usually do not choose. The system you connect to decides. What you choose is where the credential lives and how it is renewed.
| Method | What it is | What to get right |
|---|---|---|
| API key | A long-lived secret that gives access to one account. Common for internal integrations and payments (Stripe uses secret keys). | Keep it on the server only. Use a separate key for test and live. Know how to rotate it. |
| OAuth 2.0 | The user grants your app access to their account in the other system. Your app receives an access token and often a refresh token. Defined in RFC 6749. | Store tokens on the server, encrypted. Refresh before they expire. Handle revoked access. In browser or mobile flows, use the authorization code flow with PKCE. |
| Session token | Some APIs ask you to exchange long-lived credentials for a short-lived token that you send on each request. | Create it on the server, reuse it until it expires, and create a new one when the API says it is no longer valid. |
The rule that matters for every method: the browser never holds a credential that can act on behalf of your company. The user logs in to your app. Your server talks to the other system.
Where should API keys and secrets live?
On the server side, in the platform's secret store or environment variables. Never in frontend code, never in the repository, never in a variable that ends up in the browser bundle.
This is the most common mistake in AI-built apps, and it is easy to make by accident. Lovable and many other tools build the frontend with Vite. Vite's documentation says it plainly: variables prefixed with VITE_ are exposed in client-side code, and they should not contain sensitive information such as API keys (Vite: env variables and modes). If your Stripe secret key or accounting token is in a VITE_ variable, anyone can read it in their browser's developer tools.
Where to put them instead:
- Lovable: use the Secrets manager. Lovable's docs say secrets are injected into your edge functions and never reach the browser (Lovable: Secrets).
- Supabase edge functions: set secrets in the dashboard or with
supabase secrets set, and read them withDeno.env.get(Supabase: environment variables). - Your own backend: environment variables or a secret manager from your hosting provider. The OWASP Secrets Management Cheat Sheet is a good reference.
A minimal pattern: the frontend calls your own function, the function checks who the user is, then calls the other system with a key the browser never sees.
// supabase/functions/create-invoice/index.ts
// Runs on the server. The browser calls this function, never the accounting API directly.
Deno.serve(async (req: Request) => {
const apiKey = Deno.env.get("ACCOUNTING_API_KEY");
if (!apiKey) {
return new Response("Server is missing configuration", { status: 500 });
}
// 1. Check that the caller is a logged-in user who may do this.
// (With Supabase, verify the user's JWT from the Authorization header.)
// 2. Validate the input. Never forward the request body as-is.
const { orderId } = await req.json();
if (typeof orderId !== "string") {
return new Response("Invalid input", { status: 400 });
}
// 3. Call the other system with the server-side key.
// Replace the URL with the real endpoint from the provider's API docs.
const res = await fetch("https://api.example.com/invoices", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ orderId }),
});
return new Response(await res.text(), { status: res.status });
});If a secret has ever been in frontend code or in a public repository, assume it is compromised. Rotate it in the other system first, then fix the code.
How do I handle webhooks safely?
A webhook is the other system calling your app when something happens: a payment succeeded, an order was created, a listing changed. Four rules cover most of the problems.
- Verify that the request is genuine. Most providers sign webhooks with a shared secret. Check the signature against the raw request body before you trust anything in it. Stripe, for example, signs every event in the
Stripe-Signatureheader and requires the raw, unmodified body for verification (Stripe: webhooks). - Acknowledge fast. Return a 2xx response quickly and do the slow work afterwards. If your handler times out, the sender treats the delivery as failed and tries again.
- Expect duplicates. Webhooks are retried. Stripe retries failed deliveries in live mode for up to three days and notes that endpoints may occasionally receive the same event more than once.
- Do not rely on order. Events can arrive out of order. Stripe states that it does not guarantee delivery order. If you need the current state, fetch it from the API.
Use the provider's official library to verify signatures when one exists, because each provider signs differently. Stripe, for example, signs the timestamp together with the body and checks how old the timestamp is. If you have to verify an HMAC signature yourself, it looks roughly like this:
import { createHmac, timingSafeEqual } from "node:crypto";
// Generic HMAC-SHA256 check. Check your provider's docs for exactly
// what is signed, which header holds the signature and how it is encoded.
export function isValidSignature(
rawBody: string,
signatureHex: string,
secret: string,
): boolean {
const expected = createHmac("sha256", secret).update(rawBody, "utf8").digest();
const received = Buffer.from(signatureHex, "hex");
// Constant-time comparison; lengths must match first.
return received.length === expected.length && timingSafeEqual(received, expected);
}Then store the event and acknowledge it. A separate worker processes stored events, so a slow accounting API never makes the webhook time out:
// Webhook endpoint: verify, store once, acknowledge. Process later.
export async function receiveWebhook(rawBody: string, signature: string) {
const secret = process.env.WEBHOOK_SECRET;
if (!secret || !isValidSignature(rawBody, signature, secret)) {
return { status: 400 };
}
const event = JSON.parse(rawBody) as { id: string; type: string };
// webhook_inbox has a UNIQUE constraint on event_id,
// so a second delivery of the same event is simply ignored.
await db.query(
`INSERT INTO webhook_inbox (event_id, type, payload, status)
VALUES ($1, $2, $3, 'pending')
ON CONFLICT (event_id) DO NOTHING`,
[event.id, event.type, rawBody],
);
return { status: 200 };
}The worker picks up pending rows, does the work, and marks each row done or failed with the error message. Failed rows are what you alert on.
How do I stop duplicates?
Duplicates come from three places: retried webhooks, retried outgoing requests, and two systems that both create the same customer. Each has its own fix.
- Incoming events: store the event ID with a unique constraint, as above.
- Outgoing creates: before creating something in the other system, check whether you already did. Store the other system's ID next to your own record (for example
orders.external_invoice_id). If the API supports idempotency keys, send one. Stripe accepts anIdempotency-Keyheader on POST requests, so a retried request does not create a second object (Stripe: idempotent requests). - Shared records: match on a stable identifier (an organisation number, an email, an external ID), not on a name typed by a person.
// Create the invoice in the other system at most once per order.
async function createInvoiceOnce(order: { id: string; total: number }) {
const { rows } = await db.query(
"SELECT external_invoice_id FROM orders WHERE id = $1",
[order.id],
);
if (rows[0]?.external_invoice_id) return rows[0].external_invoice_id;
const res = await fetchWithRetry("https://api.example.com/invoices", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.ACCOUNTING_API_KEY}`,
"Content-Type": "application/json",
// Only helps if the API supports idempotency keys. Check its docs.
"Idempotency-Key": `invoice-${order.id}`,
},
body: JSON.stringify({ reference: order.id, amount: order.total }),
});
if (!res.ok) throw new Error(`Invoice failed: ${res.status} ${await res.text()}`);
const created = (await res.json()) as { id: string };
await db.query(
"UPDATE orders SET external_invoice_id = $1 WHERE id = $2",
[created.id, order.id],
);
return created.id;
}What about pagination and rate limits?
Almost every API returns lists in pages and limits how many requests you can make. AI-written code often reads the first page only, and gives up or hammers the API when it hits a limit.
- Read the provider's docs for how paging works (page numbers, offsets or cursors) and loop until there are no more pages.
- On HTTP 429 (too many requests) and 5xx errors, wait and retry with a growing delay. If the response has a
Retry-Afterheader, respect it. - Only retry requests that are safe to repeat: reads, or writes protected by an idempotency key or an "already done?" check.
- For large syncs, sync only what changed since the last run instead of everything every time, if the API lets you filter by change date.
// Retry on 429 and 5xx with exponential backoff. Respects Retry-After (in seconds).
export async function fetchWithRetry(
url: string,
init: RequestInit,
maxAttempts = 5,
): Promise<Response> {
for (let attempt = 1; ; attempt++) {
const res = await fetch(url, init);
const retryable = res.status === 429 || res.status >= 500;
if (!retryable || attempt >= maxAttempts) return res;
const retryAfter = Number(res.headers.get("Retry-After"));
const delayMs =
Number.isFinite(retryAfter) && retryAfter > 0
? retryAfter * 1000
: Math.min(30_000, 500 * 2 ** attempt) + Math.random() * 250;
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
// Read every page from a paged endpoint. Adapt to the API's paging style.
export async function fetchAllPages<T>(
getPage: (cursor?: string) => Promise<{ items: T[]; next?: string }>,
): Promise<T[]> {
const all: T[] = [];
let cursor: string | undefined;
do {
const page = await getPage(cursor);
all.push(...page.items);
cursor = page.next;
} while (cursor);
return all;
}How do I test without touching live data?
Use the provider's test or sandbox environment, with its own credentials, and keep test and live configuration completely separate.
- Stripe has sandboxes and separate test and live API keys (Stripe: API keys, Stripe: testing). The Stripe CLI can forward webhook events to your local machine.
- Tripletex has a separate test environment at api-test.tripletex.tech, and its docs note that accounts and tokens created for the test environment cannot be used in production (Tripletex: getting started). More on Tripletex on our Tripletex integration page.
- Test the failure cases on purpose: send the same webhook twice, revoke a token, cut the network halfway through a sync, send an invalid VAT code.
- Before going live, run the integration on a small slice of real data and compare the result with what your accountant or sales team expects.
What should I log and monitor?
Enough to answer "what happened to this order?" without guessing. For every call to another system, log the time, the operation, your own record ID, the other system's ID, the HTTP status and the error message. Never log tokens, full card data or more personal data than you need.
Then set up alerts for:
- failed webhook events or sync jobs (the
failedrows above), - a sync that has not run successfully for longer than expected,
- repeated authentication errors (401/403), which usually mean an expired or revoked token,
- a sudden jump in 429 responses.
Decide who gets the alert. An alert that goes to nobody is the same as no alert.
Which system is the source of truth?
Decide this for every type of data before you write the sync. If two systems can both edit the same customer, you will get conflicts, and no code can tell which version is right.
A simple rule set works for most small businesses: accounting data (customers with invoices, invoices, VAT, payments) is owned by the accounting system. Deals and contacts are owned by the CRM. Orders are owned by the shop. Your app reads from the owner and writes back only through clearly defined actions. In our ClickUp and Tripletex integration, Tripletex is the source of truth for customers, contacts and projects, and ClickUp only receives them.
A prompt to audit your own integration
Paste this into Claude Code, Cursor or Lovable's chat with your project open. It will not replace a review by a developer, but it finds the most common gaps.
Review this project's integrations with external systems (APIs, webhooks,
payments, accounting, CRM). For each integration, report:
1. Secrets: is any API key, token or secret in frontend code, in a VITE_
or other client-exposed variable, or committed to the repository?
2. Auth: where are access tokens stored, how are they refreshed, and what
happens when one expires or is revoked?
3. Webhooks: is every incoming webhook signature verified against the raw
body before use? Does the handler respond quickly and process later?
4. Duplicates: what happens if the same webhook or request arrives twice?
Are event IDs or external IDs stored with a unique constraint?
5. Errors: are 429 and 5xx responses retried with backoff? Are non-safe
requests retried without an idempotency key?
6. Pagination: are all pages read, or only the first?
7. Source of truth: for each type of data, which system owns it, and can
both systems overwrite each other?
8. Logging: is every external call logged with status and IDs, without
logging secrets or unnecessary personal data? Are failures alerted?
List concrete findings with file names and line numbers. Do not change
any code yet. Mark each finding as critical, important or minor.Fix critical findings first, and check each fix yourself. An AI tool reviewing its own code tends to miss the same things it missed when writing it.
When to bring in a developer
You can fix a lot yourself with this guide. Bring in a developer when:
- the integration moves money or creates accounting entries (invoices, payments, VAT),
- it handles personal data of customers or employees,
- the audit prompt finds secrets in the frontend, unverified webhooks or no duplicate protection, and you are not sure the fix is right,
- the sync runs both ways, or more than two systems are involved,
- other people in the company now depend on the app every day.
A Code Audit is the smallest step: an engineer reviews your code and walks you through what is solid and what is risky. If you need the integration built or finished, see integrations for AI-built apps. Usually you keep your app; we fix and build what is around it.
Related reading: You built an app with Claude. Now what?, You have vibe-coded an app. But is it safe? and Vibe coding done correctly. Before you switch anything on, go through our production checklist for integrations.
Related guides
- Add Stripe payments to an AI-built app safely
- Send leads from your AI-built app to Pipedrive
- Connect your AI-built app to Shopify
- Tripletex API authentication and session tokens
- The FINN API for builders
- Briefs for your AI coding tool: Tripletex, Stripe and CRM
FAQ
Can Lovable or Bolt call an external API directly from the frontend?
Technically yes, but only for public APIs that need no secret. Any call that needs an API key or token belongs in an edge function or backend, because everything in the frontend can be read by the user.
Is an API key in a Supabase edge function safe?
Safer, if it is stored as a secret and read with Deno.env.get, and the function checks who is calling it. A function that anyone can call without logging in still lets anyone use your key indirectly.
Do I need a queue for webhooks?
Not a separate product. A database table with a unique event ID and a status column, processed by a scheduled function, is enough for most small apps.
How do I know if my sync created duplicates?
Search the other system for records with the same external reference, organisation number or email. If you never stored an external reference, that is the first thing to fix.
Should I use n8n or Make.com instead of code?
For simple one-way flows, often yes: they handle retries and logging for you. The same rules still apply: source of truth, duplicate checks and alerts. We have built integrations both ways, for example a FINN.no to Webflow sync in n8n.

