Express HTML Minification Middleware

raw JSON →
2.0.0 verified Thu Apr 23 auth: no javascript

express-minify-html-2 is an Express.js middleware designed to automatically minify HTML responses rendered by an Express application, optimizing them for size. It functions as a maintained fork of the original `express-minify-html` package, explicitly created to keep the project alive and address issues like using outdated dependencies, most notably by integrating `html-minifier-terser` for robust and secure HTML minification. The current stable version is `2.0.0`. While it doesn't adhere to a strict release cadence, updates are released reactively for dependency upgrades, security fixes, and minor feature enhancements. The middleware either replaces Express's default `res.render` method with a minified version or provides an alternative `res.renderMin` function when the `override` option is set to `false`. This ensures that HTML served to clients is optimized for load times and bandwidth efficiency through configurable minification options passed directly to the underlying `html-minifier-terser` library.

error Error: Cannot find module 'html-minifier-terser'
cause The `html-minifier-terser` package or its dependencies failed to install correctly, often due to an incompatible Node.js version (e.g., running Node.js < 14.0.0) or corrupted `node_modules`.
fix
Ensure your Node.js version is 14.0.0 or higher. Run npm install or npm ci again to re-install dependencies. Check npm logs for specific installation failures.
error TypeError: app.use is not a function
cause This error typically indicates that `app` is not a valid Express application instance or has not been correctly initialized as `express()` before `app.use` is called.
fix
Verify that app = express() is called and app is correctly instantiated before attempting to use middleware with app.use().
error HTML is not minified, or minification is inconsistent for certain routes.
cause This can be caused by incorrect `override` settings, misconfigured `exceptionUrls`, or `htmlMinifier` options not being applied as expected, or an incorrect `Content-Type` header being sent.
fix
Check the override option: true should minify all res.render calls. If override: false, ensure you're explicitly calling res.renderMin. Verify exceptionUrls array correctly excludes paths you want to minify, or that it is empty if you want all paths to be minified. Debug htmlMinifier options by starting with a minimal configuration. Ensure the response Content-Type is text/html.
breaking Version 2.0.0 and above require Node.js 14.0.0 or higher. Previous versions claimed compatibility with Node.js 4.0.0, but the underlying `html-minifier-terser` dependency mandates Node.js >=14.13.1.
fix Upgrade your Node.js environment to version 14.0.0 or later. If using an older Node.js, you must stick to `express-minify-html-2` < 2.0.0, though this is not recommended due to other breaking/security changes.
breaking Version 1.0.2 replaced the deprecated and potentially insecure `html-minifier` library with `html-minifier-terser` due to identified security vulnerabilities in the former. Users on `v1.0.1` or older are exposed to these risks.
fix Immediately upgrade to `express-minify-html-2` version 1.0.2 or later to benefit from the security fix and use the actively maintained `html-minifier-terser`.
gotcha The `override` option (defaulting to `true`) determines whether the middleware hijacks the standard `res.render` function or adds a new `res.renderMin` function. Setting `override: false` requires you to explicitly call `res.renderMin`.
fix Choose `override: true` if you want all `res.render` calls to be minified automatically. If you need selective minification, set `override: false` and explicitly call `res.renderMin` where minification is desired.
gotcha Configuration options for minification are passed directly to `html-minifier-terser` via the `htmlMinifier` property. Developers should consult the `html-minifier-terser` documentation for a complete list of available options and their behaviors.
fix Refer to the official `html-minifier-terser` repository or documentation for detailed explanations of all available minification options (e.g., `removeComments`, `collapseWhitespace`, `minifyJS`, etc.).
gotcha The `exception_url` option (for URLs to skip minification) has been aliased to `exceptionUrls` in v2.0.0 for camelCase consistency. While `exception_url` is still supported for backward compatibility, `exceptionUrls` is the preferred modern spelling.
fix Update your configuration to use `exceptionUrls` for new projects or when refactoring. Ensure you pass an array of strings, regexes, or functions as documented.
npm install express-minify-html-2
yarn add express-minify-html-2
pnpm add express-minify-html-2

Demonstrates how to integrate `express-minify-html-2` into an Express application to automatically minify rendered HTML output. It configures the middleware with common minification options and shows how it intercepts `res.render`.

const express = require('express');
const minifyHTML = require('express-minify-html-2');
const path = require('path');

const app = express();

// Basic view engine setup for demonstration
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); // Using EJS as an example

// Create a dummy view file for testing (e.g., views/helloTemplate.ejs)
// Ensure 'views' directory exists and 'helloTemplate.ejs' is present
// Example helloTemplate.ejs:
// <html><body>  <h1>Hello, <%= hello %>! </h1> <p>This is a test.</p>  </body></html>

app.use(
  minifyHTML({
    override: true,
    exceptionUrls: [], // No exceptions for this example
    htmlMinifier: {
      removeComments: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeEmptyAttributes: true,
      minifyJS: true,
      minifyCSS: true
    },
  }),
);

app.get('/hello', function (req, res, next) {
  res.render('helloTemplate', { hello: 'world' }, function (err, html) {
    if (err) return next(err);
    console.log('Minified HTML output:', html);
    res.send(html);
  });
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}/hello`);
  console.log('Ensure you have an EJS template at ./views/helloTemplate.ejs');
});