> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/EvolutionAPI/evolution-api/llms.txt
> Use this file to discover all available pages before exploring further.

# Delete Instance

> Permanently delete a WhatsApp instance and all associated data

## DELETE /instance/delete/:instanceName

Permanently delete a WhatsApp instance. This will log out the instance, disconnect from WhatsApp, remove all stored data, and deactivate all integrations associated with the instance.

<Warning>
  **This action is irreversible.** All instance data including messages, contacts, settings, and integrations will be permanently deleted. The instance cannot be recovered after deletion.
</Warning>

### Authentication

This endpoint requires authentication via the `apikey` header.

```bash theme={null}
apikey: YOUR_API_KEY
```

### Path Parameters

<ParamField path="instanceName" type="string" required>
  Name of the instance you want to delete. This is the `instanceName` you specified when creating the instance.
</ParamField>

### Response

<ResponseField name="status" type="string">
  Status of the deletion operation: `SUCCESS`
</ResponseField>

<ResponseField name="error" type="boolean">
  Indicates if an error occurred: `false` on success
</ResponseField>

<ResponseField name="response" type="object">
  Response details

  <ResponseField name="message" type="string">
    Confirmation message: `Instance deleted`
  </ResponseField>
</ResponseField>

### What Gets Deleted

When you delete an instance, the following data and configurations are permanently removed:

* **WhatsApp session**: Instance is logged out from WhatsApp
* **Instance data**: All database records for the instance
* **Messages and chats**: All message history and chat data
* **Contacts**: All contact information
* **Media files**: All stored media (images, videos, documents)
* **Settings**: All instance-specific settings
* **Integrations**: All configured integrations (webhooks, Chatwoot, etc.)
* **Event subscriptions**: All webhook and event system subscriptions
* **Cached data**: All Redis/cache entries for the instance

### Examples

<CodeGroup>
  ```bash Delete Instance theme={null}
  curl -X DELETE "https://api.example.com/instance/delete/my-instance" \
    -H "apikey: YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const instanceName = 'my-instance';

  const response = await fetch(
    `https://api.example.com/instance/delete/${instanceName}`,
    {
      method: 'DELETE',
      headers: {
        'apikey': 'YOUR_API_KEY'
      }
    }
  );

  const result = await response.json();

  if (result.status === 'SUCCESS') {
    console.log('Instance deleted successfully');
  } else {
    console.error('Failed to delete instance:', result.message);
  }
  ```

  ```javascript JavaScript - With Confirmation theme={null}
  const instanceName = 'my-instance';

  // Show confirmation dialog
  if (confirm(`Are you sure you want to delete "${instanceName}"? This action cannot be undone.`)) {
    try {
      const response = await fetch(
        `https://api.example.com/instance/delete/${instanceName}`,
        {
          method: 'DELETE',
          headers: {
            'apikey': 'YOUR_API_KEY'
          }
        }
      );
      
      const result = await response.json();
      
      if (result.status === 'SUCCESS') {
        console.log('Instance deleted successfully');
        // Remove from UI, redirect, etc.
      } else {
        throw new Error(result.message || 'Deletion failed');
      }
    } catch (error) {
      console.error('Error deleting instance:', error);
      alert('Failed to delete instance. Please try again.');
    }
  }
  ```

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

  instance_name = 'my-instance'

  response = requests.delete(
      f'https://api.example.com/instance/delete/{instance_name}',
      headers={'apikey': 'YOUR_API_KEY'}
  )

  result = response.json()

  if result['status'] == 'SUCCESS':
      print('Instance deleted successfully')
  else:
      print(f"Failed to delete instance: {result.get('message')}")
  ```

  ```python Python - With Confirmation theme={null}
  import requests

  instance_name = 'my-instance'

  # Confirm deletion
  confirm = input(f'Are you sure you want to delete "{instance_name}"? (yes/no): ')

  if confirm.lower() == 'yes':
      response = requests.delete(
          f'https://api.example.com/instance/delete/{instance_name}',
          headers={'apikey': 'YOUR_API_KEY'}
      )
      
      result = response.json()
      
      if result['status'] == 'SUCCESS':
          print('Instance deleted successfully')
      else:
          print(f"Failed to delete instance: {result.get('message')}")
  else:
      print('Deletion cancelled')
  ```

  ```php PHP theme={null}
  <?php
  $instanceName = 'my-instance';

  $context = stream_context_create([
      'http' => [
          'method' => 'DELETE',
          'header' => 'apikey: YOUR_API_KEY'
      ]
  ]);

  $response = file_get_contents(
      "https://api.example.com/instance/delete/{$instanceName}",
      false,
      $context
  );

  $result = json_decode($response, true);

  if ($result['status'] === 'SUCCESS') {
      echo "Instance deleted successfully\n";
  } else {
      echo "Failed to delete instance: " . $result['message'] . "\n";
  }
  ?>
  ```

  ```php PHP - With Confirmation theme={null}
  <?php
  $instanceName = 'my-instance';

  // In a web context, you'd use JavaScript for confirmation
  // This is a CLI example
  echo "Are you sure you want to delete '{$instanceName}'? (yes/no): ";
  $confirm = trim(fgets(STDIN));

  if (strtolower($confirm) === 'yes') {
      $context = stream_context_create([
          'http' => [
              'method' => 'DELETE',
              'header' => 'apikey: YOUR_API_KEY'
          ]
      ]);
      
      $response = file_get_contents(
          "https://api.example.com/instance/delete/{$instanceName}",
          false,
          $context
      );
      
      $result = json_decode($response, true);
      
      if ($result['status'] === 'SUCCESS') {
          echo "Instance deleted successfully\n";
      } else {
          echo "Failed to delete instance: " . $result['message'] . "\n";
      }
  } else {
      echo "Deletion cancelled\n";
  }
  ?>
  ```
</CodeGroup>

### Response Examples

```json Success Response theme={null}
{
  "status": "SUCCESS",
  "error": false,
  "response": {
    "message": "Instance deleted"
  }
}
```

```json Error - Instance Not Found theme={null}
{
  "error": true,
  "message": "The \"my-instance\" instance does not exist"
}
```

```json Error - Unauthorized theme={null}
{
  "error": true,
  "message": "Unauthorized"
}
```

### Deletion Process

When you call this endpoint, the following steps are executed:

1. **Validate instance exists** - Check that the instance exists and you have permission
2. **Check connection state** - Determine if instance is connected
3. **Logout from WhatsApp** - If connected or connecting, perform logout
4. **Clear cache** - Remove all cached data (Redis, Chatwoot cache)
5. **Send webhook notification** - Trigger `INSTANCE_DELETE` webhook event
6. **Remove from registry** - Remove instance from active instances list
7. **Delete database records** - Remove all instance data from database
8. **Delete files** - Remove stored media and session files
9. **Return confirmation** - Confirm successful deletion

### Webhook Notification

If you have webhooks configured, you'll receive an `INSTANCE_DELETE` event:

```json INSTANCE_DELETE Event theme={null}
{
  "event": "INSTANCE_DELETE",
  "instance": "my-instance",
  "data": {
    "instanceName": "my-instance",
    "instanceId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
  }
}
```

<Note>
  The webhook is sent before final deletion, so your webhook handler can perform cleanup tasks or logging.
</Note>

### Error Handling

The API returns standard HTTP status codes:

* `200` - Success (instance deleted)
* `400` - Bad request (instance doesn't exist or deletion failed)
* `401` - Unauthorized (invalid API key or no permission)
* `500` - Internal server error

Common error scenarios:

1. **Instance doesn't exist**: The specified instance name is not found
2. **Permission denied**: Your API key doesn't have access to this instance
3. **Deletion in progress**: Another deletion request is already being processed
4. **Database error**: Temporary issue with database connection

### Best Practices

<Note>
  **Always confirm before deletion**: Implement a confirmation step in your UI to prevent accidental deletions.
</Note>

<Note>
  **Export data first**: If you need to preserve any data, export it before deleting the instance.
</Note>

<Note>
  **Update your records**: Remove the instance from your application's database or configuration after successful deletion.
</Note>

<Note>
  **Revoke webhooks**: The instance will no longer send webhooks after deletion, so update your webhook handlers accordingly.
</Note>

### Alternative: Logout Without Deletion

If you want to disconnect from WhatsApp without deleting the instance, use the logout endpoint instead:

```bash theme={null}
curl -X DELETE "https://api.example.com/instance/logout/my-instance" \
  -H "apikey: YOUR_API_KEY"
```

This will:

* Disconnect from WhatsApp
* Preserve all instance data and settings
* Allow you to reconnect later

### Recovery Options

<Warning>
  **No recovery after deletion**: Once an instance is deleted, it cannot be recovered. You will need to:

  1. Create a new instance with a different name
  2. Scan a new QR code to connect
  3. Reconfigure all settings and integrations
  4. You'll lose all message history and contacts from the deleted instance
</Warning>

### Rate Limiting

To prevent accidental mass deletions:

* Maximum 10 deletions per minute
* Maximum 100 deletions per hour

If you need to delete more instances, contact support for assistance.

### Security Considerations

1. **API key security**: Use instance-specific tokens when possible to limit deletion scope
2. **Audit logging**: Log all deletion requests for security and compliance
3. **Two-factor confirmation**: Consider implementing additional verification for deletion in production
4. **Role-based access**: Restrict deletion permissions to administrators only

### Use Cases

**Development Testing**

```javascript theme={null}
// Clean up test instances after integration tests
const testInstances = ['test-instance-1', 'test-instance-2'];
for (const instance of testInstances) {
  await deleteInstance(instance);
}
```

**User Requested Deletion**

```javascript theme={null}
// Handle user request to delete their WhatsApp connection
async function handleUserDeletion(userId, instanceName) {
  // Verify ownership
  if (await verifyInstanceOwnership(userId, instanceName)) {
    await deleteInstance(instanceName);
    await updateUserDatabase(userId, { instanceDeleted: true });
  }
}
```

**Subscription Cancellation**

```javascript theme={null}
// Delete instances when subscription ends
async function handleSubscriptionCancelled(subscription) {
  const instances = await getInstancesBySubscription(subscription.id);
  for (const instance of instances) {
    await deleteInstance(instance.name);
  }
}
```
