Express HTML Minification Middleware
raw JSON →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.
Common errors
error Error: Cannot find module 'html-minifier-terser' ↓
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 ↓
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. ↓
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. Warnings
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. ↓
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. ↓
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`. ↓
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. ↓
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. ↓
Install
npm install express-minify-html-2 yarn add express-minify-html-2 pnpm add express-minify-html-2 Imports
- minifyHTML wrong
import { minifyHTML } from 'express-minify-html-2'correctimport minifyHTML from 'express-minify-html-2' - minifyHTML
const minifyHTML = require('express-minify-html-2') - ConfigOptions wrong
import { Options } from 'express-minify-html-2'correctimport type { Options } from 'express-minify-html-2'
Quickstart
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');
});