# v4 code migration: Updating global middlewares

This guide is part of the v4 code migration guide designed to help you migrate the code of a Strapi application from v3.6.x to v4.0.x.

🤓 v3/v4 comparison

Strapi v4 only introduces small modifications to the structure of a global middleware, allowing for additional configuration parameters to be passed without the need to manually pull in the configuration via the Strapi API.

The configuration of middlewares has changed (see configuration migration).

The strapi generate interactive CLI is the recommended way to create a new middleware:

  1. Run yarn strapi generate in a terminal.
  2. Using the interactive CLI, choose where the middleware should apply and give it a name.
  3. Add customizations to the generated file.
Example of a Strapi v3 middleware converted to v4:
// path: ./my-custom-packages/my-custom-middleware/lib/index.js

module.exports = async (ctx, next) => {
  const start = Date.now();

  await next();

  const delta = Math.ceil(Date.now() - start);
  ctx.set('X-Response-Time', delta + 'ms');
};
1
2
3
4
5
6
7
8
9
10

The Strapi v3 global middleware example above should be converted to a Strapi v4 middleware using the following code:


// path: ./src/middlewares/my-custom-middleware.js

module.exports = (config, { strapi }) => {
  return async (ctx, next) => {
    const start = Date.now();

    await next();

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

    let headerName = config.headerName || 'X-Response-Time';
    ctx.set(headerName, delta + 'ms');
  };
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15