Skip to content

Commit

Permalink
Refactor webpack-dev-server middleware application logic
Browse files Browse the repository at this point in the history
This commit refactors the middleware application logic in the webpack-dev-server codebase to ensure that middleware is applied only once, regardless of how many times it's called. 

Previously, certain middleware, such as static serving middleware, was being applied multiple times to support features like `historyApiFallback`. This refactor eliminates duplicate middleware application by introducing a mechanism to track applied middleware and applying each middleware only once.

Changes:
- Introduced `appliedMiddleware` array to track applied middleware.
- Created `applyMiddlewareOnce` function to apply middleware only if it hasn't been applied before.
- Updated webpack-dev-server codebase to utilize `applyMiddlewareOnce` for applying middleware associated with various features.

This update aims to improve code efficiency and prevent unintended behavior or performance issues caused by duplicate middleware application.

Fixes: webpack#2716
  • Loading branch information
Swapnilden committed Apr 11, 2024
1 parent 9fddbb9 commit a39fb68
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/Server.js
Expand Up @@ -552,6 +552,35 @@ class Server {
searchParams.set("password", webSocketURL.password);
}

// Initialize an array to keep track of applied middleware
const appliedMiddleware = [];

// Function to apply middleware only once
function applyMiddlewareOnce(middleware) {
// Check if the middleware has already been applied
if (!appliedMiddleware.includes(middleware)) {
// Apply the middleware
this.app.use(middleware);

// Add the middleware to the applied middleware array
appliedMiddleware.push(middleware);
}
}

// Apply middleware for each feature only once
if (this.options.proxy) {
applyMiddlewareOnce.call(this, proxyMiddleware);
}

if (this.options.contentBase !== false) {
applyMiddlewareOnce.call(this, contentBaseMiddleware);
}

if (this.options.historyApiFallback) {
applyMiddlewareOnce.call(this, historyApiFallbackMiddleware);
}


/** @type {string} */
let hostname;

Expand Down

0 comments on commit a39fb68

Please sign in to comment.