Middlewares customization
We are currently reworking the Backend Customization section of the Strapi documentation. If you would like to help, please feel free to fill in this form to share with us your opinions, needs and requests.
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:
- with the interactive CLI command
strapi generate
- or manually by creating a JavaScript file in the appropriate folder (see project structure):
./src/middlewares/
for application-level middlewares./src/api/[api-name]/middlewares/
for API-level middlewares./src/plugins/[plugin-name]/middlewares/
for plugin middlewares
Middlewares working with the REST API are functions like the following:
- JavaScript
- TypeScript
module.exports = (config, { strapi })=> {
return (context, next) => {};
};
export default (config, { strapi })=> {
return (context, next) => {};
};
Globally scoped custom middlewares should be added to the middlewares configuration file or Strapi won't load them.
API level and plugin middlewares can be added into the specific router that they are relevant to like the following:
module.exports = {
routes: [
{
method: "GET",
path: "/[collection-name]",
handler: "[controller].find",
config: {
middlewares: ["[middleware-name]"],
// See the usage section below for middleware naming conventions
},
},
],
};
Example of a custom timer middleware
- JavaScript
- TypeScript
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');
};
};
export default () => {
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
To list all the registered middlewares, run yarn strapi middlewares:list
.