Skip to content

Custom Middleware

Parris Khachi edited this page Nov 5, 2017 · 1 revision

Fervor uses Koa under the hood. Koa is a server that provides a nice middleware interface. Sometimes, you'll want to supply custom middleware. Perhaps you want to serve something custom from some URL, and it doesn't make sense to use React. One example might be when you need to serve a XML for some 3rd party. In those cases you'll want to create either a file called src/middleware/index.js or src/middleware.js.

Here's an example middleware file:

import KoaRouter from 'koa-router';

const helloWorld = () => {
  const router = new KoaRouter();

  router.get('/hello-world', async (ctx) => {
    ctx.body = 'Hello World';
  });

  return router.routes();
};

export default ({ app }) => {
  app.use(helloWorld());
};

I'd recommend using this very wisely. With great power comes great responsibility. You could totally prevent Router or GraphQL routes from working if you override them using this functionality.