title: Middleware

In the previous chapter, we say that Egg is based on Koa, so the form of middleware in Egg is the same as in Koa, i.e. they are both based on the onion model.

Writing Middleware

How to write

Let’s take a look at how to write a middleware from a simple gzip example.

  1. const isJSON = require('koa-is-json');
  2. const zlib = require('zlib');
  3. async function gzip(ctx, next) {
  4. await next();
  5. // convert the response body to gzip after the completion of the execution of subsequent middleware
  6. let body = ctx.body;
  7. if (!body) return;
  8. if (isJSON(body)) body = JSON.stringify(body);
  9. // set gzip body, correct the response header
  10. const stream = zlib.createGzip();
  11. stream.end(body);
  12. ctx.body = stream;
  13. ctx.set('Content-Encoding', 'gzip');
  14. }

You might find that the middleware’s style in the framework is exactly the same as in Koa, yes, any middleware in Koa can be used directly by the framework.

Configuration

Usually the middleware has its own configuration. In the framework, a complete middleware includes the configuration process. A middleware is a single file placed under app/middleware directory, which needs to exports a function that accepts two parameters:

  • options: the configuration field of the middleware, app.config[${middlewareName}] will be passed in by the framework
  • app: the Application instance of current application

We will do a simple optimization to the gzip middleware above, making it do gzip compression only if the body size is greater than a configured threshold. So, we need to create a new file gzip.js in app/middleware directory.

  1. // app/middleware/gzip.js
  2. const isJSON = require('koa-is-json');
  3. const zlib = require('zlib');
  4. module.exports = options => {
  5. return async function gzip(ctx, next) {
  6. await next();
  7. // convert the response body to gzip after the completion of the execution of subsequent middleware
  8. let body = ctx.body;
  9. if (!body) return;
  10. // support options.threshold
  11. if (options.threshold && ctx.length < options.threshold) return;
  12. if (isJSON(body)) body = JSON.stringify(body);
  13. // set gzip body, correct the response header
  14. const stream = zlib.createGzip();
  15. stream.end(body);
  16. ctx.body = stream;
  17. ctx.set('Content-Encoding', 'gzip');
  18. };
  19. };

Using Middleware

After writing middleware, we also need to mount it, there are following ways to support:

Using Middleware in Application

We can load customized middleware completely by configuration in the application, and decide their order.
If we need to load the gzip middleware in the above,
we can edit config.default.js like this:

  1. module.exports = {
  2. // configure the middleware you need, which loads in the order of array
  3. middleware: [ 'gzip' ],
  4. // configure the gzip middleware
  5. gzip: {
  6. threshold: 1024, // skip response body which size is less than 1K
  7. },
  8. };

This config will be merged to app.config.appMiddleware at starting up.

Using Middleware in Framework and Plugin

Framework and Plugin don’t support to configure middleware in config.default.js, you should mount it in app.js:

  1. // app.js
  2. module.exports = app => {
  3. // put to the first place to count request cost
  4. app.config.coreMiddleware.unshift('report');
  5. };
  6. // app/middleware/report.js
  7. module.exports = () => {
  8. return async function (ctx, next) {
  9. const startTime = Date.now();
  10. await next();
  11. reportTime(Date.now() - startTime);
  12. }
  13. };

Middlewares which are defined at Application (app.config.appMiddleware) and Framework(app.config.coreMiddleware) will be merged to app.middleware by loader at staring up.

Using Middleware in Router

The middleware configured in the above ways is global, and it will process every request.

If you do want to take effect only for single route, you could just instantiate and mount it at app/router.js:

  1. module.exports = app => {
  2. const gzip = app.middleware.gzip({ threshold: 1024 });
  3. app.router.get('/needgzip', gzip, app.controller.handler);
  4. };

Default Framework Middleware

In addition to application layer loading middleware, the framework itself and other plugins will also load many middlewares. All the config fields of these built-in middlewares can be modified by modifying the ones with the same name in the config file, for example Framework Built-in Plugin uses a bodyParser middleware(the framework loader will change the various delimiters in the file name into the camel style), and we can add configs below in config/config.default.js to modify the bodyParser:

  1. module.exports = {
  2. bodyParser: {
  3. jsonLimit: '10m',
  4. },
  5. };

Note: middleware loaded by the framework and plugins are loaded earlier than those loaded by the application layer, and the application-layer middleware cannot overwrite the default framework middleware. If the application layer loads customized middleware that has the same name with default framework middleware, an error will be reported on starting up.

Use Koa’s Middleware

Developer is free to use Koa Middleware, all middlewares used in Koa can be directly used in the framework too.

For example, Koa uses koa-compress in this way:

  1. const koa = require('koa');
  2. const compress = require('koa-compress');
  3. const app = koa();
  4. const options = { threshold: 2048 };
  5. app.use(compress(options));

We can load the middleware according to the framework specification like this:

  1. // app/middleware/compress.js
  2. // interfaces(`(options) => middleware`) exposed by koa-compress match the framework middleware requirements
  3. module.exports = require('koa-compress');
  1. // config/config.default.js
  2. module.exports = {
  3. middleware: [ 'compress' ],
  4. compress: {
  5. threshold: 2048,
  6. },
  7. };

If the third-party Koa middleware do not follow the rule, then you can wrap it yourself:

  1. // config/config.default.js
  2. module.exports = {
  3. webpack: {
  4. compiler: {},
  5. others: {},
  6. },
  7. };
  8. // app/middleware/webpack.js
  9. const webpackMiddleware = require('some-koa-middleware');
  10. module.exports = (options, app) => {
  11. return webpackMiddleware(options.compiler, options.others);
  12. }

General Configuration

These general config fields are supported by middleware loaded by the application layer and built in by the framework:

  • enable: enable the middleware or not
  • match: set some rules with which only the request matches can go through this middleware
  • ignore: set some rules with which the request matches can’t go through this middleware

enable

If our application does not need default bodyParser to resolve the request body, we can configure enable for false to close it.

  1. module.exports = {
  2. bodyParser: {
  3. enable: false,
  4. },
  5. };

match and ignore

match and ignore share the same parameter but do the opposite things. match and ignore cannot be configured in the same time.

If we want gzip to be used only by url requests starting with /static, the match config field can be set like this:

  1. module.exports = {
  2. gzip: {
  3. match: '/static',
  4. },
  5. };

match and ignore support various types of configuration ways:

  1. String: when string, it sets the prefix of a url path, and all urls starting with this prefix will be matched.
  2. Regular expression: when regular expression, all urls satisfy this regular expression will be matched.
  3. Function: when function, the request context will be passed to it and what it returns(true/false) determines whether the request is matched or not.
  1. module.exports = {
  2. gzip: {
  3. match(ctx) {
  4. // enabled on ios devices
  5. const reg = /iphone|ipad|ipod/i;
  6. return reg.test(ctx.get('user-agent'));
  7. },
  8. },
  9. };