Errors

API error codes and handling

5 min read

Error Handling

Flonk API uses standard HTTP status codes and returns detailed error information.

Error Response Format

Error bodies are flat. statusCode and message are always present; code is a stable, machine-branchable identifier present on the documented failures below (and expanding over time):

json
{
"statusCode": 404,
"code": "session_not_found",
"message": "Session sess_123 not found or does not belong to your project",
"timestamp": "2026-06-03T00:00:00.000Z"
}

Branch on code, not on message text (messages may change; codes are stable).

HTTP Status Codes

CodeDescription
200Success
400Bad Request - Invalid parameters
401Unauthorized - Invalid or missing API key
402Payment Required - No free verifications or balance left (session creation)
403Forbidden - Access denied
404Not Found - Resource doesn't exist
429Too Many Requests - Rate limit exceeded
500Internal Server Error

Error Codes

Authentication Errors

A bad secret key returns 401 with a plain message and no code: Secret key required for server-to-server API access, Invalid secret key format. Expected sk_live_*, sk_sandbox_*, or sk_test_*, or Invalid or inactive secret key. Branch on the status. The SDK throws FlonkAuthenticationError for every 401.

Forbidden (403)

Also without a code. On POST /v1/sessions: the project is not approved yet for live sessions (the body has moderationStatus), or a check your workflow uses is not enabled for your account (the body has disabledChecks).

Session Errors

CodeStatusDescription
session_not_found404Session ID doesn't exist or isn't in your project
session_expired400Session has passed its expiry
session_invalid_state400Session can't be used/updated in its current state (completed/failed/non-pending)

Payment Required (402)

POST /v1/sessions (and the widget's session start) returns 402 when the project cannot pay for another verification. A verification is paid from your free verifications first, then from your balance and credit. Test-mode sessions (made with sk_test_* keys) are not charged unless Flonk has switched on charging for test mode on your project. Sessions made with sk_sandbox_* keys are real verifications and are charged like live ones.

New accounts get 300 free verifications with no end date. Each completed verification uses one; test sessions made with your test keys are not charged by default. When they run out, top up in Dashboard → Billing.

The body is flat like the others but has no code. Branch on error ("Payment Required") and then on reason when it is present:

reasonMeaningWhat to do
paid_usage_not_confirmedThe free verifications are over and paid usage has not been confirmed yetConfirm paid usage in Dashboard → Billing
monthly_limitThe project's monthly spend or verification limit is reachedAsk the project owner to raise the limit in Billing
none (the body has availableBalance, creditLimit, required, trialExpired)Not enough balance for this sessionTop up in Dashboard → Billing
json
{
"statusCode": 402,
"error": "Payment Required",
"message": "Insufficient balance. Please top up your project balance.",
"availableBalance": 0,
"currentBalance": 0,
"creditLimit": 0,
"required": 1.5,
"trialExpired": true,
"timestamp": "2026-11-07T00:00:00.000Z"
}

The values are only an illustration. A 402 is not retried by the SDK; retrying without topping up gets the same answer. See Free trial & billing.

The code field is also exposed by the SDK as error.code (typed FlonkErrorCode, an open union) — see below.

Handling Errors

Using the SDK

The SDK throws typed error classes that you can catch and handle:

typescript
import { FlonkKYCServer } from '@flonkid/kyc/server';
import {
FlonkAuthenticationError,
FlonkValidationError,
FlonkAPIError,
} from '@flonkid/kyc/types';
const flonk = new FlonkKYCServer({ secretKey: '...' });
try {
const session = await flonk.createSession({
clientMetadata: { email: 'user@example.com' },
});
} catch (error) {
if (error instanceof FlonkAuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof FlonkValidationError) {
console.error('Invalid request:', error.message);
} else if (error instanceof FlonkAPIError) {
// Branch on the stable code, not the message text.
switch (error.code) {
case 'session_not_found': /* … */ break;
case 'session_expired': /* re-create the session */ break;
default: console.error(`API error ${error.statusCode}:`, error.message);
}
}
}

error.code is typed FlonkErrorCode (an open union), so a switch stays type-safe while tolerating codes added later.

Manual (fetch)

typescript
try {
const response = await fetch('https://api.flonk.id/v1/sessions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${secretKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 401:
console.error('Invalid API key');
break;
case 402:
console.error('No free verifications or balance left:', error.reason ?? error.message);
break;
case 429:
console.error('Rate limited, retry later');
break;
default:
console.error('API error:', error.message);
}
}
} catch (error) {
console.error('Network error:', error);
}

Retry Strategy

The SDK retries transient errors (429 / 5xx / network) for you with jittered exponential backoff, honouring Retry-After. GETs always retry; writes retry only when idempotent. Tune or disable via new FlonkKYCServer({ maxRetries }).

If you call the API manually, implement backoff yourself:

typescript
async function fetchWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const response = await fetch(url, options);
if (response.status === 429 || response.status >= 500) {
const delay = Math.pow(2, i) * 1000;
await new Promise(r => setTimeout(r, delay));
continue;
}
return response;
}
throw new Error('Max retries exceeded');
}