External APIs & webhooks

Connect your app to external REST APIs and incoming webhooks safely using server-side authentication, cryptographic signature verification, timeouts, and idempotent event handling.

How outbound APIs and inbound webhooks differ

Real apps rarely operate alone. Booking apps query calendars, stores calculate carrier rates, SaaS tools alert Slack channels, and marketplaces react to signed contracts or cleared payments. Almost every integration uses one of two directions.

An outbound REST API call starts from your backend server. A user triggers an action, your UI calls your own backend route, and your server sends an authenticated HTTP request upstream and returns sanitized JSON.

An inbound webhook starts from the external provider. When something finishes asynchronously later — a payment clears, a shipment delivers, or a document gets signed — the provider sends an HTTP POST request to your server endpoint.

Choosing the right integration pattern

Picking the right pattern up front prevents slow screens, flaky browser errors, and missed state updates.

PatternDirectionBest suited forCore reliability safeguard
Server-side REST proxyYour server to providerShipping quotes, address validation, CRM lookups, AI completionsExplicit 5–8s timeout, server key, calm fallback UI
Signed inbound webhookProvider to your serverPayment confirmations, renewals, e-signature completion, shipping eventsCryptographic signature check plus idempotent event table
Cached background fetchYour server on scheduleExchange rates, weather widgets, rate-limited public catalogsCache upstream JSON in Cloud and refresh periodically
Hosted redirect handoffBrowser to provider and backStripe Checkout, OAuth login, identity verification portalsNever trust return URL params alone; confirm via webhook

Returning to /checkout/success?paid=true never proves a charge succeeded because any visitor can type that URL manually. Treat redirect pages as navigation convenience and verified server webhooks as truth.

Calling external REST APIs from server routes

Authenticating outbound requests cleanly

Read credentials solely from server-side environment variables. Most REST services use one of three auth header patterns:

  • Bearer token. Authorization: Bearer <token> — standard across modern SaaS, AI, and payment APIs.
  • Custom key header. X-API-Key: <token> or provider-specific token headers.
  • HTTP Basic auth. Base64-encoded username:password header used by services such as Twilio.

See Secrets & API keys for isolating Preview sandbox keys from Live credentials.

Timeouts, validation, and safe retries

Never allow a slow upstream API to freeze your interface indefinitely. Configure an explicit timeout (5–8 seconds for interactive forms) and validate upstream JSON before writing to Cloud.

  • Never retry `400`, `401`, `403`, or `404`. These indicate bad input, invalid credentials, or missing records; repeating them wastes quota.
  • Retry `429` and `502`/`503`/`504` sparingly. Use at most one or two short backoff retries (300ms, then 900ms) on idempotent GET requests or writes carrying a provider idempotency key.
  • Return calm UI errors. Log upstream status codes server-side and display clear fallback copy to visitors.

Step-by-step outbound API integration

  1. Check the provider's sandbox docs

    Confirm base URL, auth header, rate limits, and exact success/error JSON shapes.

  2. Save the sandbox key in Preview

    Store the test token under a clear uppercase name such as CARRIER_API_KEY.

  3. Build a server proxy route

    Validate user auth and form inputs, attach the server secret, enforce a timeout, and return minimal JSON fields.

  4. Verify failure paths in Preview

    Test invalid input and simulated timeouts to ensure the UI shows a friendly retry state.

  5. Add the Live key before Publish

    Save the production credential in Live settings, publish, and run one end-to-end check.

Starter prompt · App

Create a backend route POST /api/address/verify requiring a signed-in user. Validate street, city, postalCode, and country, call our address verification REST API with process.env.ADDRESS_API_KEY as a Bearer token and a 5-second timeout, and return normalized fields plus isValid. If upstream returns 429 or times out, return HTTP 503 with a clear message letting the user continue manually.

Receiving and verifying incoming webhooks

Because webhook routes accept public POST traffic, anyone on the internet can post forged JSON pretending an order was paid. Never execute business logic before verifying the cryptographic signature.

HMAC signature verification rules

When registering an endpoint with Stripe, GitHub, Resend, or DocuSign, the provider supplies a shared webhook signing secret. Each delivery includes an HMAC-SHA256 signature computed over the exact raw request bytes and delivery timestamp.

http
POST /api/webhooks/esign HTTP/1.1
Host: yourdomain.com
Content-Type: application/json
X-Provider-Timestamp: 1735689600
X-Provider-Signature: t=1735689600,v1=8c4f9b2e7a1d6f0e3a9c5b4d2e1f8a7c...

{"id":"evt_91f8a2","type":"document.signed","data":{"contract_id":"ctr_442"}}

Enforce four rules in every webhook route:

  • Capture exact raw body bytes. Parsing JSON first and re-stringifying alters spacing or key order, breaking valid HMAC checks.
  • Verify digests in constant time. Compute the expected HMAC-SHA256 with your server signing secret and reject mismatches with 401 Unauthorized.
  • Enforce a replay window. Reject timestamps older than 5 minutes so intercepted deliveries cannot be replayed later.
  • Return `200 OK` quickly. Persist and respond in under 3 seconds so providers do not treat slow replies as failures.

Handling retries and idempotency

Providers deliver webhooks at least once. If a brief network blip drops your 200 OK response, the provider resends the identical event minutes later.

Without idempotency, retries send duplicate receipts, grant double credits, or create duplicate shipments. Prevent duplicates with a webhook_events table in Cloud carrying a unique constraint on (provider, provider_event_id).

json
{
  "table": "webhook_events",
  "columns": {
    "id": "uuid primary key",
    "provider": "text not null",
    "provider_event_id": "text not null",
    "event_type": "text not null",
    "processed_at": "timestamp with time zone",
    "status": "text not null"
  },
  "unique_constraint": ["provider", "provider_event_id"]
}

Insert (provider, event.id) when a verified webhook arrives. If the unique constraint rejects it as already recorded, return 200 OK immediately without repeating the action.

Starter prompt · App

Build POST /api/webhooks/shipping reading the raw request body, verifying X-Carrier-Signature (HMAC-SHA256) against process.env.CARRIER_WEBHOOK_SECRET within a 5-minute window, and returning 401 on invalid signatures. Create a Cloud table webhook_events with a unique index on (provider, provider_event_id) so duplicate deliveries return 200 OK immediately without double-updating orders or resending delivery emails.

For payment webhooks and subscription lifecycles, see Testing Stripe & webhooks.

Common mistakes and troubleshooting

SymptomRoot causeExact fix
Browser shows CORS blocked errorFrontend called the third-party API directlyMove the request into a server /api/... route and call that route from the UI
Webhook always fails with 401Body parsed to JSON before HMAC verification, or Live/Preview secrets swappedRead raw request bytes first and verify the secret matches the exact registered endpoint
Duplicate emails or double row updatesProvider retried after timeout and route lacks idempotencyStore provider_event_id in a unique-indexed webhook_events table and skip duplicates
Form hangs for 30+ secondsOutbound REST call has no explicit timeoutAdd a 5–8 second timeout with a clean fallback error response
Webhooks fire in Preview, never on LiveProvider still points only to Preview URLRegister https://yourdomain.com/api/webhooks/... in the provider's Live dashboard with Live secrets

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog