Skip to main content

Middlewares customization

Different types of middlewares

In Strapi, 2 middleware concepts coexist:

  • Strapi middlewares are configured and enabled for the entire Strapi server application. These middlewares can be applied at the application level or at the API level.
    The present documentation describes how to implement them.
    Plugins can also add Strapi middlewares (see Server API documentation).

  • Route middlewares have a more limited scope and are configured and used as middlewares at the route level. They are described in the routes documentation.

Implementation

A new application-level or API-level middleware can be implemented:

Middlewares working with the REST API are functions like the following:

./src/middlewares/my-middleware.js or ./src/api/[api-name]/middlewares/my-middleware.js

module.exports = (config, { strapi })=> {
return (context, next) => {};
};

Once created, custom middlewares should be added to the middlewares configuration file or Strapi won't load them.

Example of a custom timer middleware
path: /config/middlewares.js
module.exports = () => {
return async (ctx, next) => {
const start = Date.now();

await next();

const delta = Math.ceil(Date.now() - start);
ctx.set('X-Response-Time', delta + 'ms');
};
};

The GraphQL plugin also allows implementing custom middlewares, with a different syntax.

Usage

Middlewares are called different ways depending on their scope:

  • use global::middleware-name for application-level middlewares
  • use api::api-name.middleware-name for API-level middlewares
  • use plugin::plugin-name.middleware-name for plugin middlewares
tip

To list all the registered middlewares, run yarn strapi middlewares:list.