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

# Middleware

> Intercept agent requests and responses

Agents can use middleware to process requests and responses - for logging, validation, or transformation.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Request Pipeline"
        A[📤 Input] --> B[🔧 Middleware]
        B --> C[🤖 Agent]
        C --> D[🔧 Middleware]
        D --> E[📥 Output]
    end

    classDef agent fill:#8B0000,color:#fff
    classDef tool fill:#189AB4,color:#fff

    class C agent
    class A,B,D,E tool
```

## Quick Start

<Steps>
  <Step title="Simple Usage">
    ```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import { Agent, Middleware } from 'praisonai';

    const logger: Middleware = async (ctx, next) => {
      console.log('Input:', ctx.input);
      await next();
      console.log('Output:', ctx.output);
    };

    const agent = new Agent({
      instructions: 'You are helpful',
      middleware: [logger]
    });
    ```
  </Step>

  <Step title="With Configuration">
    ```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    const validate: Middleware = async (ctx, next) => {
      if (ctx.input.length > 1000) {
        throw new Error('Input too long');
      }
      await next();
    };
    ```
  </Step>
</Steps>

***

## User Interaction Flow

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant MW1 as Logger
    participant Agent
    participant MW2 as Filter
    
    User->>MW1: Request
    MW1->>Agent: Log + forward
    Agent-->>MW2: Response
    MW2-->>User: Filter + forward
```

***

## Configuration Levels

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
// Level 1: Array - Middleware list
const agent = new Agent({
  middleware: [logger, validator]
});

// Level 2: Function - Simple middleware
const agent = new Agent({
  middleware: [
    async (ctx, next) => {
      console.log(ctx.input);
      await next();
    }
  ]
});

// Level 3: Instance - Full control
const agent = new Agent({
  middleware: [
    {
      name: 'logger',
      handler: loggerFn,
      order: 1
    },
    {
      name: 'cache',
      handler: cacheFn,
      order: 2
    }
  ]
});
```

***

## Common Uses

| Use Case       | Description                    |
| -------------- | ------------------------------ |
| Logging        | Track all requests/responses   |
| Validation     | Check inputs before processing |
| Transformation | Modify data in transit         |
| Caching        | Cache frequent responses       |

***

## API Reference

<Card title="HooksConfig" icon="code" href="/docs/sdk/reference/typescript/classes/HooksConfig">
  Hooks configuration (middleware pattern)
</Card>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Keep middleware focused">
    Each middleware should do one thing well.
  </Accordion>

  <Accordion title="Order matters">
    Middleware runs in order - put validation first.
  </Accordion>

  <Accordion title="Always call next()">
    Forgetting next() breaks the chain.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Hooks" icon="webhook" href="/docs/js/hooks-manager">
    Lifecycle hooks
  </Card>

  <Card title="Guardrails" icon="shield" href="/docs/js/guardrails">
    Input validation
  </Card>
</CardGroup>
