Skip to content

Creating middleware

Lloyd Brookes edited this page Jul 9, 2017 · 12 revisions

Local-web-server uses Koa as its middleware engine so it would help to first read the Koa guide to writing middleware.

This is the minimum code to create a middleware module. A middleware module exports a function which returns a class extending MiddlewareBase (a superclass supplied by ws). The only required method is middleware which is passed the active ws configuration and must return a Koa middleware function.

This example sets the response body to 'Hello'. Save it to a file named mw-example.js.

module.exports = MiddlewareBase => class Example extends MiddlewareBase {
  middleware (options) {
    return (ctx, next) => {
      ctx.response.body = 'Hello'
    }
  }
}

Launch your stack with the following command. By setting --stack you override the built-in stack with the middleware supplied.

$ ws --stack mw-example.js
Serving at http://mbp.local:8100, http://127.0.0.1:8100, http://192.168.0.100:8100

Test you get the expected response.

$ curl http://127.0.0.1:8100
Hello

You can parameterise middleware by adding a optionDefinitions method which should return one or more option definitions. This example defines an option called message which will be a string.

module.exports = MiddlewareBase => class Example extends MiddlewareBase {
  optionDefinitions () {
    return [
      { name: 'message', type: String, description: 'A message to print.'}
    ]
  }
  middleware (options) {
    return (ctx, next) => {
      ctx.response.body = 'Hello'
    }
  }
}
Clone this wiki locally