> ## 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.

# Frontend Integration

This guide explains how to show Captide results in a React frontend, and open their sources in the Document Auditing SDK's viewer.

> [!NOTE]
>
> **Never expose your Captide API key in frontend code!** The examples below call the backend proxy from the [Backend Integration](https://docs.captide.ai/integration/backend.md) guide: `POST /api/chunks`, `GET /api/documents/:id` and `POST /api/agent-stream`.

## React Integration

### Basic Document Viewer Setup

Wrap your app in `DocumentViewerProvider` with a `fetchDocumentFn` that loads a document from your backend. Then call `loadDocument(documentId, { page, snippet })` to open a document at a page and highlight a passage. Here, each chunk returned for a query gets a button that opens its source:

```jsx theme={null}
import React, { useState } from 'react';
import { DocumentViewer, DocumentViewerProvider, useDocumentViewer } from 'captide';

const fetchDocument = async (documentId) => {
  const response = await fetch(`/api/documents/${documentId}`);
  if (!response.ok) throw new Error(`Failed to load document ${documentId}`);
  return response.json();
};

export default function App() {
  return (
    <DocumentViewerProvider fetchDocumentFn={fetchDocument}>
      <ChunkExplorer />
    </DocumentViewerProvider>
  );
}

function ChunkExplorer() {
  const { loadDocument } = useDocumentViewer();
  const [query, setQuery] = useState('');
  const [chunks, setChunks] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const response = await fetch('/api/chunks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query })
      });
      const data = await response.json();
      setChunks(data.relevantChunks ?? []);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="What was Apple's revenue last quarter?"
        />
        <button type="submit" disabled={isLoading}>
          {isLoading ? 'Loading...' : 'Search'}
        </button>
      </form>

      <ul>
        {chunks.map((chunk, i) => (
          <li key={i}>
            {chunk.documentMetadata.title}, page {chunk.pageNumber}{' '}
            <button
              onClick={() => loadDocument(chunk.documentMetadata.id, { page: chunk.pageNumber })}
            >
              Open
            </button>
          </li>
        ))}
      </ul>

      {/* The DocumentViewer needs to be sized explicitly */}
      <div style={{ height: '600px', marginTop: '20px', border: '1px solid #ccc' }}>
        <DocumentViewer />
      </div>
    </div>
  );
}
```

### Streaming Response Example

The agent stream is a sequence of `data:` lines, each holding a JSON event (see Example 5 in the [Quickstart](https://docs.captide.ai/integration/quickstart.md) for the event types). The example below:

* shows `thinking` events as a status line;
* builds the answer from `message` events, and replaces it with `content_final` when that arrives;
* keeps the `sources` event, which maps each citation (`#43c00004`, `#43c00004:2`, …) to its chunk;
* turns each citation into a link that opens the source page and highlights the cited excerpt.

A network read can end in the middle of a line, so the parser keeps the unfinished part until the next read.

```jsx theme={null}
import React, { useState } from 'react';
import { DocumentViewer, DocumentViewerProvider, useDocumentViewer } from 'captide';

const CITATION = /(\[#[^\]\s]+\])/g;

function AgentChat() {
  const { loadDocument } = useDocumentViewer();
  const [query, setQuery] = useState('');
  const [status, setStatus] = useState('');
  const [answer, setAnswer] = useState('');
  const [sources, setSources] = useState({});
  const [isLoading, setIsLoading] = useState(false);

  const handleEvent = (event) => {
    switch (event.type) {
      case 'thinking':
        setStatus(event.content);
        break;
      case 'message':
        setAnswer((prev) => prev + event.content);
        break;
      case 'content_final':
        setAnswer(event.content);
        break;
      case 'sources':
        setSources(event.content);
        break;
      case 'warning':
        setStatus(event.message);
        break;
      case 'done':
        setStatus('');
        break;
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setAnswer('');
    setSources({});
    try {
      const response = await fetch('/api/agent-stream', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query })
      });
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop(); // keep the unfinished line for the next read
        for (const line of lines) {
          if (line.startsWith('data: ')) handleEvent(JSON.parse(line.slice(6)));
        }
      }
    } finally {
      setIsLoading(false);
    }
  };

  const openCitation = (ref) => {
    const source = sources[ref];
    if (!source) return; // sources arrive at the end of the stream
    loadDocument(source.documentMetadata.id, {
      page: source.pageNumber,
      snippet: source.excerpt ?? undefined
    });
  };

  // Render "[#43c00004]" as a numbered link to its source
  const renderAnswer = (text) => {
    const refs = [];
    return text.split(CITATION).map((part, i) => {
      const match = part.match(/^\[(#[^\]\s]+)\]$/);
      if (!match) return <span key={i}>{part}</span>;
      const ref = match[1];
      if (!refs.includes(ref)) refs.push(ref);
      return (
        <a key={i} href="#" onClick={(e) => { e.preventDefault(); openCitation(ref); }}>
          [{refs.indexOf(ref) + 1}]
        </a>
      );
    });
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="What was Zscaler's net dollar retention in the last two quarters?"
          style={{ width: '400px' }}
        />
        <button type="submit" disabled={isLoading}>
          {isLoading ? 'Loading...' : 'Ask'}
        </button>
      </form>

      {status && <p><em>{status}</em></p>}
      <div style={{ whiteSpace: 'pre-wrap' }}>{renderAnswer(answer)}</div>

      <div style={{ height: '600px', marginTop: '20px', border: '1px solid #ccc' }}>
        <DocumentViewer />
      </div>
    </div>
  );
}

const fetchDocument = async (documentId) => {
  const response = await fetch(`/api/documents/${documentId}`);
  if (!response.ok) throw new Error(`Failed to load document ${documentId}`);
  return response.json();
};

export default function App() {
  return (
    <DocumentViewerProvider fetchDocumentFn={fetchDocument}>
      <AgentChat />
    </DocumentViewerProvider>
  );
}
```

The answer is Markdown. In a real application, render it with a Markdown renderer (such as `react-markdown`) and replace citations with links in its output.

## Next.js Integration

With Next.js, the proxy routes can be route handlers. This one serves documents to the viewer, mapped to the SDK's `Document` fields:

```javascript theme={null}
// app/api/documents/[id]/route.js
export async function GET(request, { params }) {
  const { id } = await params;
  const response = await fetch(
    `https://rest-api.captide.co/api/v2/documents/${encodeURIComponent(id)}`,
    { headers: { 'X-API-Key': process.env.CAPTIDE_API_KEY } }
  );
  const doc = await response.json();
  if (!response.ok) {
    return Response.json(doc, { status: response.status });
  }

  return Response.json({
    ...doc,
    formType: doc.secFormType,
    tickers: doc.companyTickers,
    fileType: new URL(doc.originalFileUrl).pathname.endsWith('.pdf') ? 'pdf' : 'html',
    metadata: { ...doc.metadata, sourceURL: doc.metadata?.sourceUrl }
  });
}
```


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