Tilted sphere with longitudinal stripes Modern Web Guides Docs Blog Toggle darkmode

Dev Server: Middleware

You can add your own middleware to the dev server using the middleware property. The middleware should be a standard koa middleware. Read more about koa here.

You can use middleware to modify responses to any request from the browser, for example, to rewrite a URL or proxy to another server. For serving or manipulating files it's recommended to use plugins.

Proxying requests

Read more
import proxy from 'koa-proxies';

export default {
  port: 9000,
  middleware: [
    proxy('/api', {
      target: 'http://localhost:9001',
    }),
  ],
};

Enabling range requests

You can add the capability to handle range request using koa-range. This is often needed to seek audio or video media.

Read more

Install with npm install --save-dev koa-range.

import range from 'koa-range';

export default {
...
  middleware: [
    range
  ]
};

Rewriting request urls

You can rewrite certain file requests using a middleware. This can be useful for example to serve your index.html from a different file location or to alias a module.

Read more

Serve /index.html from /src/index.html:

export default {
  middleware: [
    function rewriteIndex(context, next) {
      if (context.url === '/' || context.url === '/index.html') {
        context.url = '/src/index.html';
      }

      return next();
    },
  ],
};

Reusing express middleware

It's possible to reuse middleware written in express using an adapter such as express-to-koa.