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

# Delete Thread

> Manually end and delete a conversation thread

## Overview

Manually deletes a conversation thread before its automatic 30-minute expiration. Use this to:

* End conversations when users log out
* Clean up threads when a session ends
* Protect privacy by removing conversation history
* Free up server resources

<Warning>
  **Permanent Deletion:** This action cannot be undone. All messages in the thread will be permanently deleted.
</Warning>

### Authentication

<ParamField header="X-API-Key" type="string" required>
  Your Cura API key
</ParamField>

### Path Parameters

<ParamField path="id" type="string" required>
  The 5-digit thread ID to delete (e.g., `82451`)
</ParamField>

## Request Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X DELETE "https://api.mycura.org/api/cura/threads/82451" \
    -H "X-API-Key: YOUR_API_KEY"
  ```

  ```javascript Node.js theme={null}
  const axios = require('axios');

  const response = await axios.delete(
    'https://api.mycura.org/api/cura/threads/82451',
    {
      headers: {
        'X-API-Key': 'YOUR_API_KEY'
      }
    }
  );

  console.log(response.data.message);
  // "Thread deleted successfully"
  ```

  ```python Python theme={null}
  import requests

  response = requests.delete(
      'https://api.mycura.org/api/cura/threads/82451',
      headers={
          'X-API-Key': 'YOUR_API_KEY'
      }
  )

  print(response.json()['message'])
  # "Thread deleted successfully"
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init('https://api.mycura.org/api/cura/threads/82451');
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'X-API-Key: YOUR_API_KEY'
  ]);

  $response = curl_exec($ch);
  $data = json_decode($response, true);
  echo $data['message'];
  ?>
  ```
</CodeGroup>

## Response

<ResponseField name="success" type="boolean">
  Whether the deletion was successful
</ResponseField>

<ResponseField name="message" type="string">
  Confirmation message
</ResponseField>

### Success Response (200)

```json theme={null}
{
  "success": true,
  "message": "Thread deleted successfully"
}
```

## Error Responses

<ResponseExample>
  ```json 404 Not Found theme={null}
  {
    "error": "Thread not found"
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "error": "Unauthorized - Invalid API key"
  }
  ```

  ```json 500 Internal Server Error theme={null}
  {
    "error": "Failed to delete thread"
  }
  ```
</ResponseExample>

## When to Delete Threads

<CardGroup cols={2}>
  <Card title="User Logs Out" icon="right-from-bracket" color="#ef4444">
    Delete threads when users end their session for privacy
  </Card>

  <Card title="Conversation Complete" icon="check-circle" color="#10b981">
    Clean up when the conversation naturally concludes
  </Card>

  <Card title="Starting Fresh" icon="rotate" color="#3b82f6">
    Delete old thread before creating a new one for the same user
  </Card>

  <Card title="Error Recovery" icon="triangle-exclamation" color="#f59e0b">
    Remove problematic threads to start clean
  </Card>
</CardGroup>

## Common Use Cases

### 1. Delete on Logout

```javascript theme={null}
// Clean up thread when user logs out
async function handleLogout() {
  const threadId = sessionStorage.getItem('threadId');
  
  if (threadId) {
    try {
      await axios.delete(
        `https://api.mycura.org/api/cura/threads/${threadId}`,
        {
          headers: { 'X-API-Key': 'YOUR_API_KEY' }
        }
      );
      console.log('Thread deleted successfully');
    } catch (error) {
      console.error('Failed to delete thread:', error);
    } finally {
      sessionStorage.removeItem('threadId');
    }
  }
  
  // Proceed with logout
  await logout();
}
```

### 2. Delete on Browser Close

```javascript theme={null}
// Clean up thread when user closes the browser/tab
window.addEventListener('beforeunload', async (event) => {
  const threadId = sessionStorage.getItem('threadId');
  
  if (threadId) {
    // Use sendBeacon for guaranteed delivery
    const blob = new Blob(
      [JSON.stringify({ threadId })],
      { type: 'application/json' }
    );
    
    navigator.sendBeacon(
      'https://yourapp.com/api/cleanup-thread',
      blob
    );
    
    // Your backend should call DELETE /api/cura/threads/{id}
  }
});
```

### 3. Auto-Delete After Success

```javascript theme={null}
// Delete thread after successful task completion
async function completeRefillRequest(threadId) {
  // Process refill through conversation
  await chat({ 
    threadId, 
    message: "I'd like to refill my medication" 
  });
  
  // ... more conversation ...
  
  // Once refill is confirmed, clean up
  await axios.delete(
    `https://api.mycura.org/api/cura/threads/${threadId}`,
    {
      headers: { 'X-API-Key': 'YOUR_API_KEY' }
    }
  );
  
  console.log('Refill complete, thread deleted');
}
```

### 4. Replace Expired Thread

```javascript theme={null}
// Check if thread expired, delete and create new one
async function ensureActiveThread(oldThreadId) {
  try {
    // Try to get thread info
    await axios.get(
      `https://api.mycura.org/api/cura/threads/${oldThreadId}`,
      {
        headers: { 'X-API-Key': 'YOUR_API_KEY' }
      }
    );
    
    // Thread still exists, return it
    return oldThreadId;
    
  } catch (error) {
    if (error.response?.status === 404) {
      // Thread expired/deleted - create new one
      const newThread = await createThread();
      return newThread.threadId;
    }
    throw error;
  }
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Always clean up on logout">
    Delete threads when users log out or close sessions to protect privacy:

    ```javascript theme={null}
    auth.onLogout(async () => {
      if (currentThreadId) {
        await deleteThread(currentThreadId);
      }
    });
    ```
  </Accordion>

  <Accordion title="Handle deletion failures gracefully">
    Don't block user actions if thread deletion fails:

    ```javascript theme={null}
    try {
      await deleteThread(threadId);
    } catch (error) {
      // Log error but don't prevent logout
      console.error('Thread cleanup failed:', error);
    }
    // Continue with user action regardless
    proceedWithLogout();
    ```
  </Accordion>

  <Accordion title="Use sendBeacon for browser close">
    For reliable cleanup on page unload, use `navigator.sendBeacon()`:

    ```javascript theme={null}
    window.addEventListener('beforeunload', () => {
      if (threadId) {
        // This is guaranteed to send even if page is closing
        navigator.sendBeacon(
          '/api/cleanup',
          JSON.stringify({ threadId })
        );
      }
    });
    ```
  </Accordion>

  <Accordion title="Track deletion in analytics">
    Monitor how users are ending conversations:

    ```javascript theme={null}
    async function deleteThread(threadId) {
      await axios.delete(
        `https://api.mycura.org/api/cura/threads/${threadId}`,
        {
          headers: { 'X-API-Key': 'YOUR_API_KEY' }
        }
      );
      
      // Track the deletion
      analytics.track('thread_deleted', {
        threadId,
        trigger: 'user_action',
        timestamp: new Date().toISOString()
      });
    }
    ```
  </Accordion>
</AccordionGroup>

## Automatic Deletion

<Note>
  **Reminder:** Threads automatically delete after 30 minutes of inactivity. You don't need to manually delete every thread - this endpoint is for when you want to end a conversation early.
</Note>

The auto-deletion system:

* Runs every 10 minutes on the server
* Deletes threads inactive for 30+ minutes
* Resets the timer every time a message is sent
* Permanently removes all conversation data

## Related Endpoints

<CardGroup cols={3}>
  <Card title="Create Thread" icon="plus" href="/api-reference/endpoint/create-thread">
    Start a new conversation
  </Card>

  <Card title="Get Thread" icon="circle-info" href="/api-reference/endpoint/get-thread">
    Check thread status
  </Card>

  <Card title="Chat" icon="message" href="/api-reference/endpoint/chat">
    Send messages to a thread
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Conversation Threads Guide" icon="book" href="/conversation-threads">
    Learn about thread lifecycle and management
  </Card>

  <Card title="Best Practices" icon="lightbulb" href="/best-practices">
    Tips for production applications
  </Card>
</CardGroup>
