Learn how to handle errors when working with the Lightfast API.

Error Response Format

All errors follow a consistent JSON structure:

json
{
  "error": "UNAUTHORIZED",
  "message": "Authentication required. Provide 'Authorization: Bearer <api-key>' header or sign in.",
  "requestId": "req_abc123xyz"
}
FieldDescription
errorError code (uppercase)
messageHuman-readable error description
requestIdUnique request ID for debugging

Error Codes

INVALID_JSON (400)

The request body contains invalid JSON.

json
{
  "error": "INVALID_JSON",
  "message": "Failed to parse request body as JSON",
  "requestId": "req_abc123"
}

Common causes:

  • Malformed JSON syntax
  • Missing closing brackets or quotes
  • Invalid escape sequences

VALIDATION_ERROR (400)

Request parameters failed schema validation.

json
{
  "error": "VALIDATION_ERROR",
  "message": "Query must not be empty",
  "requestId": "req_abc123"
}

Common causes:

  • Missing required fields (e.g., query for search)
  • Invalid parameter types
  • Values outside allowed ranges (e.g., limit > 100)

BAD_REQUEST (400)

The request is missing required headers.

json
{
  "error": "BAD_REQUEST",
  "message": "Workspace ID required. Provide 'X-Workspace-ID: <workspace-id>' header.",
  "requestId": "req_abc123"
}

Common causes:

  • Missing X-Workspace-ID header
  • Empty workspace ID value

UNAUTHORIZED (401)

Authentication failed or was not provided.

json
{
  "error": "UNAUTHORIZED",
  "message": "Authentication required. Provide 'Authorization: Bearer <api-key>' header or sign in.",
  "requestId": "req_abc123"
}

Common causes:

  • Missing Authorization header
  • Invalid API key
  • Expired or revoked API key
  • Incorrect Bearer prefix

FORBIDDEN (403)

The authenticated user does not have access to the workspace.

json
{
  "error": "FORBIDDEN",
  "message": "Access denied to this workspace",
  "requestId": "req_abc123"
}

Common causes:

  • User is not a member of the workspace's organization
  • API key does not have access to the workspace

NOT_FOUND (404)

The requested resource does not exist.

json
{
  "error": "NOT_FOUND",
  "message": "Workspace not found",
  "requestId": "req_abc123"
}

Common causes:

  • Invalid workspace ID
  • Workspace was deleted
  • Content ID does not exist

METHOD_NOT_ALLOWED (405)

The HTTP method is not supported for this endpoint.

json
{
  "error": "METHOD_NOT_ALLOWED",
  "message": "Method GET not allowed. Use POST.",
  "requestId": "req_abc123"
}

Solution: All API endpoints use POST method.

CONFIG_ERROR (500)

The workspace is not properly configured.

json
{
  "error": "CONFIG_ERROR",
  "message": "Workspace not configured for search",
  "requestId": "req_abc123"
}

Solution: Ensure the workspace has connected sources and completed initial indexing.

INTERNAL_ERROR (500)

An unexpected server error occurred.

json
{
  "error": "INTERNAL_ERROR",
  "message": "An unexpected error occurred",
  "requestId": "req_abc123"
}

Solution: Retry with exponential backoff. If the error persists, contact support with the requestId.

Error Handling Examples

Basic Error Handling

typescript
const response = await fetch('https://lightfast.ai/api/v1/search', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'X-Workspace-ID': workspaceId,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ query: 'authentication' })
})

if (!response.ok) {
  const error = await response.json()

  switch (error.error) {
    case 'UNAUTHORIZED':
      console.error('Invalid or missing API key')
      break
    case 'BAD_REQUEST':
      console.error('Missing X-Workspace-ID header')
      break
    case 'FORBIDDEN':
      console.error('No access to this workspace')
      break
    case 'NOT_FOUND':
      console.error('Workspace not found')
      break
    case 'VALIDATION_ERROR':
      console.error('Invalid request:', error.message)
      break
    default:
      console.error('API error:', error.message)
  }

  return
}

const data = await response.json()

Retry with Exponential Backoff

typescript
async function fetchWithRetry(
  url: string,
  options: RequestInit,
  maxRetries = 3
) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, options)

      if (response.ok) {
        return response.json()
      }

      const error = await response.json()

      // Don't retry client errors (4xx)
      if (response.status >= 400 && response.status < 500) {
        throw new Error(`API error: ${error.message}`)
      }

      // Retry server errors (5xx)
      if (attempt < maxRetries - 1) {
        const delay = Math.pow(2, attempt) * 1000 // 1s, 2s, 4s
        console.log(`Retrying in ${delay}ms...`)
        await new Promise(r => setTimeout(r, delay))
        continue
      }

      throw new Error(`API error after ${maxRetries} retries: ${error.message}`)

    } catch (error) {
      if (attempt === maxRetries - 1) throw error
    }
  }
}

// Usage
const results = await fetchWithRetry(
  'https://lightfast.ai/api/v1/search',
  {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'X-Workspace-ID': workspaceId,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ query: 'authentication' })
  }
)

TypeScript Error Types

typescript
interface LightfastError {
  error: string
  message: string
  requestId: string
}

type ErrorCode =
  | 'INVALID_JSON'
  | 'VALIDATION_ERROR'
  | 'BAD_REQUEST'
  | 'UNAUTHORIZED'
  | 'FORBIDDEN'
  | 'NOT_FOUND'
  | 'METHOD_NOT_ALLOWED'
  | 'CONFIG_ERROR'
  | 'INTERNAL_ERROR'

function isLightfastError(data: unknown): data is LightfastError {
  return (
    typeof data === 'object' &&
    data !== null &&
    'error' in data &&
    'message' in data &&
    'requestId' in data
  )
}

async function handleResponse(response: Response) {
  const data = await response.json()

  if (!response.ok && isLightfastError(data)) {
    throw new Error(`[${data.error}] ${data.message} (requestId: ${data.requestId})`)
  }

  return data
}

Error Code Reference

CodeStatusDescriptionRetry?
INVALID_JSON400Invalid JSON bodyNo
VALIDATION_ERROR400Schema validation failedNo
BAD_REQUEST400Missing required headerNo
UNAUTHORIZED401Authentication failedNo
FORBIDDEN403Access deniedNo
NOT_FOUND404Resource not foundNo
METHOD_NOT_ALLOWED405Wrong HTTP methodNo
CONFIG_ERROR500Workspace not configuredNo
INTERNAL_ERROR500Server errorYes

Next Steps