# Middlewares

Middleware in FhyTS functions as an intermediary layer (interceptor) between requests and responses. Middleware can be used for various purposes, such as authentication, logging, parsing, validation, and caching.

## Basic Structure

Middleware in FhyTS is defined using the MiddlewareFn type, which accepts three main arguments:

```javascript
(req: Request, res: Response, next: () => Promise<void>) => Promise<void>
```

This type allows middleware to be executed asynchronously before the controller is called.

```javascript
import { MiddlewareFn, Request, Response } from 'fhyts';
```

## Simple Caching Middleware

```javascript
const cache: Record<string, string> = {};

export const CacheMiddleware: MiddlewareFn = async (req: Request, res: Response, next) => {
  const key = req.url;

  if (cache[key]) {
    res.status(200).html(cache[key]);
  } else {
    const originalSend = res.send.bind(res);
    res.send = (data: string) => {
      cache[key] = data;
      originalSend(data);
    };
    await next();
  }
};
```

## Explanation:

* **cache** stores the URL-based response as a key.
* If the URL already exists in the cache, the response is returned directly without proceeding to the controller.
* If it doesn't exist, the original response is cached via the **res.send** method override.

## Implementation in Routing

Middleware can be registered globally or per route in the routes.ts file.

```javascript
import { CacheMiddleware } from './middlewares/CacheMiddleware';

// ....

Use('GET', '/', Example.index.bind(Example), [CacheMiddleware]);
```

## Best Practices

* Middleware should be stateless unless absolutely necessary (such as caching).
* Ensure all middleware calls **await next()** unless it wants to stop the request flow.
* Use middleware to handle functions that are orthogonal to the core business (e.g., logging, rate-limiting, etc.).

## Next

Once you understand how to use Middleware, you can move on to the [Request](#request) section to learn how to handle HTTP requests in a structured and efficient manner in your application.