Middleware

Handling middleware within Octoris

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

The middleware arrays provided fire from left to right

Available Middleware

Global Stage

Middleware used at the very beginning of a route being triggered, this is provided to the composeRoutes function as the 3rd parameter

Example

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 function directly

Example

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

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

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

Last updated