> ## Documentation Index
> Fetch the complete documentation index at: https://docs.captide.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Backend Integration

This guide explains how to call the Captide API from your backend, using Node.js and Express. Your backend holds the API key and exposes the few routes your frontend needs, so the key never reaches the browser.

## Node.js Integration

### Express.js Example

The proxy below exposes three routes:

1. `POST /api/chunks` returns the chunks relevant to a query.
2. `GET /api/documents/:id` returns a document in the shape the [Document Auditing SDK](https://docs.captide.ai/integration/frontend.md) expects.
3. `POST /api/agent-stream` streams the agent's answer to the browser.

It uses the `fetch` built into Node.js 18 and later.

```typescript theme={null}
import express from 'express';
import { Readable } from 'node:stream';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
app.use(express.json());

const CAPTIDE_API_KEY = process.env.CAPTIDE_API_KEY;
const CAPTIDE_BASE_URL = 'https://rest-api.captide.co';
const captideHeaders = { 'X-API-Key': CAPTIDE_API_KEY };

// 1. Chunks relevant to a natural language query
app.post('/api/chunks', async (req, res) => {
  const response = await fetch(`${CAPTIDE_BASE_URL}/api/v2/rag/chunks`, {
    method: 'POST',
    headers: { ...captideHeaders, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: String(req.body.query ?? '') })
  });
  res.status(response.status).json(await response.json());
});

// 2. A document for the viewer. `id` is `documentMetadata.id` from a chunk or sourceMap entry.
app.get('/api/documents/:id', async (req, res) => {
  const response = await fetch(
    `${CAPTIDE_BASE_URL}/api/v2/documents/${encodeURIComponent(req.params.id)}`,
    { headers: captideHeaders }
  );
  if (!response.ok) {
    return res.status(response.status).json(await response.json());
  }

  const doc = await response.json();
  res.json({
    ...doc,
    // Field names the SDK's Document type uses
    formType: doc.secFormType,
    tickers: doc.companyTickers,
    fileType: new URL(doc.originalFileUrl).pathname.endsWith('.pdf') ? 'pdf' : 'html',
    // The viewer's Open button links to metadata.sourceURL, the document's original web address
    metadata: { ...doc.metadata, sourceURL: doc.metadata?.sourceUrl }
  });
});

// 3. The agent's answer as Server-Sent Events
app.post('/api/agent-stream', async (req, res) => {
  const upstream = new AbortController();
  res.on('close', () => upstream.abort()); // stop the upstream request if the browser disconnects

  const response = await fetch(`${CAPTIDE_BASE_URL}/api/v2/rag/agent-response-stream`, {
    method: 'POST',
    headers: { ...captideHeaders, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: req.body.query }),
    signal: upstream.signal
  });
  if (!response.ok) {
    return res.status(response.status).json(await response.json());
  }

  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  Readable.fromWeb(response.body).pipe(res);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
```

## Environment Variables and Security

Always store your API key in environment variables or a secure configuration system, never hardcode it in your application code.

Create a `.env` file in your project root:

```
CAPTIDE_API_KEY=your_api_key_here
```

Make sure to add `.env` to your `.gitignore` file to avoid committing sensitive credentials.

## Error Handling

Errors from the Captide API are JSON objects with a `detail` field, returned with a standard HTTP status. `detail` is a message, except on `422`, where it lists the invalid fields:

| Status | Meaning |
| - | - |
| `400` | A parameter is invalid (for example an unknown document category or a malformed company ID). |
| `401` | The API key is missing or invalid. |
| `403` | Your organization doesn't have access to this endpoint. |
| `402` | Your organization has no API credits left. |
| `404` | The company or document doesn't exist. |
| `422` | A parameter has the wrong type or is out of range (for example `limit` above 1000). |
| `429` | Rate limit exceeded. Retry after a pause. |
| `500` / `504` | Server error or timeout. Retry later, or narrow the request (for example add `companyTickers` to a text search). |

`fetch` doesn't throw on HTTP errors, so check `response.ok` and pass the status and `detail` on to your client, as the routes above do. Network failures (no response at all) do throw:

```typescript theme={null}
try {
  const response = await fetch(url, { headers: captideHeaders });
  if (!response.ok) {
    const { detail } = await response.json();
    return res.status(response.status).json({ error: detail });
  }
  res.json(await response.json());
} catch (error) {
  console.error('Unable to reach the Captide API:', error);
  res.status(503).json({ error: 'Unable to reach the Captide API' });
}
```

## Rate Limiting

Your API key's limits apply across everyone using your application. Rate-limit your own routes so that one user can't use them up:

```typescript theme={null}
import rateLimit from 'express-rate-limit';

const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per window
  message: 'Too many requests, please try again later'
});

// Apply to routes that call Captide
app.use('/api/chunks', apiLimiter);
app.use('/api/documents', apiLimiter);
app.use('/api/agent-stream', apiLimiter);
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.