dev.setupMiddlewares

  • Type:
type SetupMiddlewaresServer = {
  sockWrite: (
    type: string,
    data?: string | boolean | Record<string, any>,
  ) => void;
  environments: EnvironmentAPI;
};

type SetupMiddlewares = Array<
  (
    middlewares: {
      unshift: (...handlers: RequestHandler[]) => void;
      push: (...handlers: RequestHandler[]) => void;
    },
    server: SetupMiddlewaresServer,
  ) => void
>;
  • Default: undefined

Provides the ability to execute a custom function and apply custom middlewares.

Execution Order

The order among several different types of middleware is: unshift => internal middlewares => push.

export default {
  dev: {
    setupMiddlewares: [
      (middlewares, server) => {
        middlewares.unshift((req, res, next) => {
          console.log('first');
          next();
        });

        middlewares.push((req, res, next) => {
          console.log('last');
          next();
        });
      },
    ],
  },
};

Server API

In the setupMiddlewares function, you can access the server object, which provides some server APIs.

sockWrite

sockWrite allows middlewares to send some message to HMR client, and then the HMR client will take different actions depending on the message type.

For example, if you send a 'content-changed' message, the page will reload.

export default {
  dev: {
    setupMiddlewares: [
      (middlewares, server) => {
        if (someCondition) {
          server.sockWrite('content-changed');
        }
      },
    ],
  },
};

environments

environments includes Rsbuild's environment API, which allows you to get the build outputs information for a specific environment in the server side.

export default {
  dev: {
    setupMiddlewares: [
      (middlewares, server) => {
        middlewares.unshift(async (req, _res, next) => {
          const webStats = await server.environments.web.getStats();

          console.log(webStats.toJson({ all: false }));

          next();
        });
      },
    ],
  },
};