type SetupMiddlewaresContext = {
sockWrite: (
type: string,
data?: string | boolean | Record<string, any>,
) => void;
environments: EnvironmentAPI;
};
type SetupMiddlewaresFn = (
middlewares: {
unshift: (...handlers: RequestHandler[]) => void;
push: (...handlers: RequestHandler[]) => void;
},
context: SetupMiddlewaresContext,
) => void;
type SetupMiddlewares = SetupMiddlewaresFn | SetupMiddlewaresFn[];undefined>= 1.4.0Used to add custom middleware to the dev server.
See Dev server - Middleware for more information.
setupMiddlewares function receives a middlewares array, you can add custom middleware by unshift and push methods:
unshift to prepend middleware to the array, executed earlier than the built-in middleware.push to append middleware to the array, executed later than the built-in middleware.export default {
dev: {
setupMiddlewares: (middlewares) => {
middlewares.unshift((req, res, next) => {
console.log('first');
next();
});
middlewares.push((req, res, next) => {
console.log('last');
next();
});
},
},
};The middleware can be an async function:
export default {
dev: {
setupMiddlewares: (middlewares) => {
middlewares.unshift(async (req, res, next) => {
await someAsyncOperation();
next();
});
},
},
};setupMiddlewares also supports passing an array, each item of which is a function to set up middlewares:
export default {
dev: {
setupMiddlewares: [
(middlewares) => {
// ...
},
(middlewares) => {
// ...
},
],
},
};
In versions before Rsbuild 1.4.0, setupMiddlewares must pass an array.
The second parameter of the setupMiddlewares function is the context object, which provides some server context and APIs.
Provides Rsbuild's environment API, see Dev server API - environments for more details.
export default {
dev: {
setupMiddlewares: (middlewares, { environments }) => {
middlewares.unshift(async (req, _res, next) => {
const webStats = await environments.web.getStats();
console.log(webStats.toJson({ all: false }));
next();
});
},
},
};Sends some message to HMR client, see Dev server API - sockWrite for more details.
For example, if you send a 'static-changed' message, the page will reload.
export default {
dev: {
setupMiddlewares: (middlewares, { sockWrite }) => {
if (someCondition) {
sockWrite('static-changed');
}
},
},
};