How to setup custom middleware in strapi?

Viewed 6299

I just wanted to setup a simple custom middleware in strapi. I have tried what they are writing in docs but I found that environments folder and inside configurations are removed. Follwing that currently I have writtent.

/config/environments/development/middleware.json

{
  "subscribers": {
    "enabled": true
  }
}

/config/middleware.json

{
  "timeout": 100,
  "load": {
    "before": ["responseTime", "logger", "cors", "responses", "gzip"],
    "order": ["parser", "subscribers"],
    "after": ["router"]
  }
}

/middlewares/subscribers/index.js

module.exports = (strapi) => {
  return {
    initialize() {
      strapi.app.use(async (ctx, next) => {
        console.log("I have been called!");
        await next();
      });
    },
  };
};

Please help me to implement a middleware in strapi api.Thanks beforehand.

1 Answers

I just did what is written in the docs and I will do the same in my answer!

Initially I was reading from an older version of documentation which is mentioned by @Derrick Mehaffy. I found the correct docs url and read through its middleware implementation. [LINK TO THE DOCS] (Below explanations are obtained from docs)

------------------------------------------------------------------------------------

Examples: Create your custom middleware. [Path — ./middlewares/timer/index.js]

module.exports = strapi => {
  return {
    initialize() {
      strapi.app.use(async (ctx, next) => {
        const start = Date.now();
        // I just add custom code that logs `I have been called!`
        console.log('I have been called!');
        await next();

        const delta = Math.ceil(Date.now() - start);

        ctx.set('X-Response-Time', delta + 'ms');
      });
    },
  };
};

Enable the middleware in environments settings.

Load a middleware at the very first place - !You can do at the proper order

Path — ./config/middleware.js

module.exports = {
  load: {
    before: ["timer", "responseTime", "logger", "cors", "responses", "gzip"],
    order: ["parser", ],
    after: ["router", ],
  },
  settings: {
    timer: {
      enabled: true,
    },
  },
};

Basically I just copied and pasted the answer from docs, but it might be helpful for future use that's I have left the question

Related