Express HTML Minification Middleware

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

express-minify-html is an Express middleware designed to automatically minify HTML responses generated by `res.render` calls. It leverages the robust `html-minifier` library under the hood, passing configuration options directly to it. The current stable version is 0.12.0. While there's no stated release cadence, its versioning suggests a pre-1.0 status, implying potential API changes in minor versions. A key differentiator is its seamless integration with Express's existing `res.render` function, with an option to `override` it directly or expose a new `res.renderMin` method. It also supports `exception_url` configurations, allowing developers to selectively bypass minification for specific routes using strings, regular expressions, or custom functions. This helps optimize performance by reducing HTML payload size for most requests without affecting critical or dynamic paths that might be sensitive to minification.

error Error: Cannot find module 'express-minify-html'
cause The `express-minify-html` package has not been installed or is not resolvable in the current project environment.
fix
Run npm install express-minify-html in your project directory.
error TypeError: app.use is not a function
cause `app` is not an initialized Express application instance, or `express()` was not called.
fix
Ensure const express = require('express'); and const app = express(); are correctly set up before calling app.use().
error TypeError: minifyHTML is not a function
cause The `minifyHTML` symbol was imported incorrectly, often by attempting `import minifyHTML from 'express-minify-html'` in a CommonJS-first environment.
fix
Use const minifyHTML = require('express-minify-html'); to correctly import the middleware factory.
gotcha Setting the `override` option to `false` will prevent the middleware from modifying the standard `res.render` function. Instead, you must explicitly call `res.renderMin` to get minified HTML. Failing to do so will result in unminified output.
fix Either set `override: true` to have `res.render` automatically minify, or ensure all calls needing minification are updated to `res.renderMin` when `override` is `false`.
gotcha Incorrect or overly aggressive configuration of the `htmlMinifier` options can lead to broken HTML, unexpected JavaScript behavior, or styling issues on the client-side. Always test minified output thoroughly.
fix Carefully consult the official `html-minifier` documentation for recommended and safe configuration options. Start with basic options like `collapseWhitespace` and incrementally add others.
gotcha This package is designed for CommonJS (`require`). While modern Node.js environments might allow some interop, direct ESM `import` statements might not work correctly without specific bundler configurations (e.g., Webpack, Rollup) or Node.js loader setups.
fix Use `const minifyHTML = require('express-minify-html');` for consistent behavior, especially in older Node.js projects or those not configured for ESM-CJS interop.
npm install express-minify-html
yarn add express-minify-html
pnpm add express-minify-html

This quickstart demonstrates how to apply the `express-minify-html` middleware globally to an Express application, showing its effect on HTML rendered via `res.render`.

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

const app = express();

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

// Create a dummy view file (e.g., views/helloTemplate.ejs)
// console.log('Create views/helloTemplate.ejs with content like: <div>  <h1>Hello  <%= hello %></h1>  <p> This is a paragraph. </p></div>');

app.use(minifyHTML({
    override:      true,
    exception_url: [],
    htmlMinifier: {
        removeComments:            true,
        collapseWhitespace:        true,
        collapseBooleanAttributes: true,
        removeAttributeQuotes:     true,
        removeEmptyAttributes:     true,
        minifyJS:                  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:\n' + html); // The output is minified
        res.send(html);
    });
});

app.get('/', (req, res) => {
  res.send('Go to /hello to see minified HTML');
});

const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
    console.log('Ensure you have a views/helloTemplate.ejs file.');
});