# Middlewares and Params

## How middleware works?

![How middleware works](/files/xcUgKWRfQwLbvPJ9puiP)

When the bot gets update, it completes all middlewares, and only then completes a handler. For example, using middlewares, you can auth user and pass some params to the handler

## Creating middleware

Let's create `logger.middleware.ts` file. It will be the middleware that will log received update. We will then apply this middleware

{% hint style="info" %}
You can move middleware to different position

You can read more about `Answer` class [here](/nestgram/nestgram-features/answer-class.md)
{% endhint %}

{% code title="logger.middleware.ts" %}

```typescript
export function LoggerMiddleware(
  update: IUpdate, // received update
  answer: Answer, // Answer (you can send a message)
  params: any, // Params (you can pass params to the handler)
  next: NextFunction, // next function (it can be next middleware or handler)
  fail: NextFunction, // fail function (you need to call it if you don't want to call handler)
) {
  params.someParam = 1; // set some param that we want to get in handler
  console.log(update); // log received update
  next(); // call handler
}
```

{% endcode %}

{% code title="app.controller.ts" %}

```typescript
import { OnText, Controller, Params } from 'nestgram';
import { LoggerMiddleware } from './logger.middleware';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService?: AppService) {}

  @OnText()
  @Middleware(LoggerMiddleware)
  async handleText(@Params() params: any): Promise<string> {
    console.log(params);
    return 'Hello, world!';
  }
}
```

{% endcode %}

## Global middlewares

You can apply middleware for all controller, if you are uncomfortable to set it for every handler

{% code title="app.module.ts" %}

```typescript
import { Module } from 'nestgram';
import { LoggerMiddleware } from './logger.middleware.ts';

import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  controllers: [AppController],
  services: [AppService],
  middlewares: [LoggerMiddleware],
})
export class AppModule {}
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://degreetpro.gitbook.io/nestgram/nestgram-features/middlewares-and-params.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
