Skip to content
Back to skills

2521 Conditional Middleware 5b175205

ASecurity

Conditional middleware allows you to route execution to different middleware based on runtime conditions.

  • 9 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added October 11, 2026
devopspythonapi

Works with

  • api

Security analysis

A100/100

Scanned October 11, 2026

npx -y skills add tools-only/X-Skills --skill 2521-conditional-middleware_5b175205 --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of 2521 Conditional Middleware 5b175205?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for 2521 Conditional Middleware 5b175205
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/tools-only-2521-conditional-middleware-5b175205/badge)](https://www.skillsdirectory.com/skills/tools-only-2521-conditional-middleware-5b175205)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

SKILL.md
# Conditional Middleware

Conditional middleware allows you to route execution to different middleware based on runtime conditions.

## Basic Usage

Use `ConditionalMiddleware` to branch based on a predicate function:

```python
from pydantic_ai_middleware import ConditionalMiddleware

def is_admin(ctx):
    return ctx is not None and ctx.config.get("role") == "admin"

middleware = ConditionalMiddleware(
    condition=is_admin,
    when_true=AdminMiddleware(),
    when_false=UserMiddleware(),
)
```

## Predicate Functions

Predicates receive a `ScopedContext` and return a boolean:

```python
from pydantic_ai_middleware import ScopedContext, HookType

def is_after_run(ctx: ScopedContext | None) -> bool:
    return ctx is not None and ctx.current_hook == HookType.AFTER_RUN

def has_feature_flag(ctx: ScopedContext | None) -> bool:
    return ctx is not None and ctx.config.get("feature_enabled", False)
```

## Middleware Pipelines

Both branches can accept a single middleware or a sequence:

```python
middleware = ConditionalMiddleware(
    condition=is_admin,
    when_true=[AuditMiddleware(), AdminMiddleware()],  # Pipeline
    when_false=UserMiddleware(),  # Single middleware
)
```

## Optional Else Branch

The `when_false` branch is optional. When omitted, the condition acts as a guard:

```python
middleware = ConditionalMiddleware(
    condition=lambda ctx: ctx is not None and ctx.config.get("logging_enabled"),
    when_true=LoggingMiddleware(),
    # No when_false - just pass through when condition is False
)
```

## Next Steps

- [Middleware Chains](middleware-chains.md) - Sequential composition
- [Config Loading](config-loading.md) - Load pipelines from config files
- [API Reference](../api/conditional.md) - ConditionalMiddleware API

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…