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

# Middleware in FastAPI

> Middleware enables application-wide request and response processing for tasks such as logging, security, exception handling, and performance monitoring.

## What is Middleware?

Middleware is a component that sits **between the client and your application**. Every incoming request passes through the middleware before reaching the route handler, and every outgoing response passes through the middleware before being sent back to the client.

Middleware is commonly used for **application-wide processing**.

## Request-Response Flow

```text theme={null}
Client
   │
   ▼
Middleware
   │
   ▼
Route Handler
   │
   ▼
Middleware
   │
   ▼
Client
```

Middleware executes twice:

* Before the request reaches the route handler.
* After the route handler returns the response.

## Working Principle

A middleware receives two arguments:

* `request`
* `call_next`

```python theme={null}
@app.middleware("http")
async def middleware(request: Request, call_next):

    # Before Request

    response = await call_next(request)

    # After Response

    return response
```

The statement

```python theme={null}
response = await call_next(request)
```

forwards the request to the next middleware or the route handler and returns the generated response.

## Example 1 - Logging Requests

```python theme={null}
from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def logging_middleware(request: Request, call_next):

    print(f"{request.method} {request.url}")

    response = await call_next(request)

    print(response.status_code)

    return response
```

## Example 2 - Measure Request Processing Time

```python theme={null}
import time
from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def timer_middleware(request: Request, call_next):

    start = time.time()

    response = await call_next(request)

    end = time.time()

    print(f"Time: {end - start:.4f} sec")

    return response
```

## Example 3 - Global Exception Handling

```python theme={null}
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()


@app.middleware("http")
async def exception_middleware(request: Request, call_next):

    try:
        return await call_next(request)

    except Exception:
        return JSONResponse(
            status_code=500,
            content={"detail": "Internal Server Error"}
        )
```

## Frequently Used Built-in Middleware

### CORSMiddleware

Allows browser applications from trusted origins to access your API.

```python theme={null}
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://myapp.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
```

### GZipMiddleware

Compresses large responses to reduce network usage.

```python theme={null}
from fastapi.middleware.gzip import GZipMiddleware

app.add_middleware(
    GZipMiddleware,
    minimum_size=1000
)
```

## Middleware vs Dependencies

| Middleware                                                              | Dependency (`Depends`)                                                                |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| Runs for every request.                                                 | Runs only when declared.                                                              |
| Can modify requests and responses.                                      | Provides objects or services to routes.                                               |
| Suitable for logging, CORS, compression, and global exception handling. | Suitable for database sessions, authentication, authorization, and service injection. |

## Common Use Cases

* Logging requests and responses.
* Measuring request processing time.
* Global exception handling.
* CORS configuration.
* Session management.
* Response compression.

> Although authentication and authorization can be implemented using middleware, FastAPI recommends using **dependencies (`Depends`)** because different routes often require different authentication and authorization rules.

## Key Points

* Middleware intercepts every request and response.
* It executes before and after the route handler.
* `call_next()` forwards the request to the next middleware or route handler.
* FastAPI provides several built-in middleware through Starlette.
* Use middleware for application-wide concerns and dependencies for route-specific logic.
