# Middleware

Octoris supports middleware at 3 stages:

* Global Stage, this is directly after the route is hit, the only missing piece from context here is params
* Route Stage, this is middleware attached to a route directly, full context is available here
* Method Stage, This is middleware attached directly to methods on a route, full context is available here

{% hint style="info" %}
The middleware arrays provided fire from left to right
{% endhint %}

## Available Middleware

* [@octoris/static](https://www.npmjs.com/package/@octoris/static) - A static file server middleware
* [@octoris/body-parser](https://www.npmjs.com/package/@octoris/body-parser) - A body parser middleware
* [@octoris/multipart](https://www.npmjs.com/package/@octoris/multipart) - A multipart form/file middleware

## Global Stage

Middleware used at the very beginning of a route being triggered, this is provided to the [composeRoutes](https://github.com/dhershman1/octoris/wiki/Router-API#composeroutesopts-routes-middleware) function as the 3rd parameter

### Example

```javascript
const { router } = require('octoris')

router.composeRoutes({}, [route], [middlewareFn1, middlewareFn2])
```

In the above example, we have it setup so anytime we hit a route the middleware functions 1 and 2 will be called first. The functions are read from the array from **left** to **right**.

## Route Stage

Middleware in the route stage will fire immediately after the global stage middleware, these are functions attached directly to a route that will trigger regardless of what method was used. These are provided to the [route](https://github.com/dhershman1/octoris/wiki/Router-API#routeroutepath-methods-middleware) function directly

### Example

```javascript
const { methods, router } = require('octoris')

router.route([router.fixed('/')], [methods.GET(handler)], [middlewareFn])
```

## Method Stage

This stage is the last to trigger and happens AFTER the route stage. This middleware is attached specifically to a method so it only triggers when that method is used.

### Example

```javascript
const { methods, router } = require('octoris')

router.route([router.fixed('/')], [methods.GET(handler, [middlewareFn])])
```
