New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

express-compress-html

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-compress-html

Fast HTML minification middleware for Express using Rust-based @minify-html/node

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

express-compress-html

⚡ Fast HTML minification middleware for Express using Rust-based @minify-html/node

npm version License: MIT

Features

  • 🚀 Blazing Fast - Uses Rust-based minifier for optimal performance
  • 📦 Zero Configuration - Works out of the box with sensible defaults
  • 🎯 TypeScript Support - Full type definitions included
  • 🔧 Customizable - Fine-tune minification options to your needs
  • 🛡️ Error Resilient - Gracefully falls back to original HTML on errors
  • 🎨 Template Engine Agnostic - Works with EJS, Pug, Handlebars, and more
  • 🌍 Express 4.x & 5.x - Compatible with both major Express versions

Installation

npm install express-compress-html

Quick Start

JavaScript

const express = require('express');
const htmlMinifier = require('express-compress-html');

const app = express();

// Set your template engine
app.set('view engine', 'ejs');

// Use the middleware
app.use(htmlMinifier());

app.get('/', (req, res) => {
  res.render('index');
});

app.listen(3000);

TypeScript

import express from 'express';
import htmlMinifier from 'express-compress-html';

const app = express();

app.set('view engine', 'ejs');

// Use with default options
app.use(htmlMinifier());

// Or with custom options
app.use(htmlMinifier({
  enabled: true,
  minifyOptions: {
    keep_comments: false,
    minify_css: true,
    minify_js: true
  }
}));

app.get('/', (req, res) => {
  res.render('index');
});

app.listen(3000);

How It Works

The middleware intercepts res.render() calls and minifies the rendered HTML before sending it to the client. This works seamlessly with:

  • EJS
  • Pug (formerly Jade)
  • Handlebars
  • express-ejs-layouts
  • Any other Express template engine

API

htmlMinifier(options?)

Creates an Express middleware function that minifies HTML responses.

Options

enabled (boolean, optional)

Explicitly enable or disable minification. If not set, minification is automatically enabled in production (NODE_ENV=production) or when MINIFY_HTML=true.

app.use(htmlMinifier({
  enabled: true  // Always minify, regardless of NODE_ENV
}));
minifyOptions (object, optional)

Customize the minification behavior. All options are passed directly to @minify-html/node.

app.use(htmlMinifier({
  minifyOptions: {
    do_not_minify_doctype: false,
    ensure_spec_compliant_unquoted_attribute_values: false,
    keep_closing_tags: false,
    keep_html_and_head_opening_tags: false,
    keep_spaces_between_attributes: false,
    keep_comments: false,
    minify_css: true,
    minify_js: true,
    remove_bangs: false,
    remove_processing_instructions: false
  }
}));

Default Options:

OptionDefaultDescription
do_not_minify_doctypefalseDon't minify DOCTYPE declarations
ensure_spec_compliant_unquoted_attribute_valuesfalseEnsure spec-compliant unquoted attribute values
keep_closing_tagsfalseKeep closing tags (e.g., </div>, </span>)
keep_html_and_head_opening_tagsfalseKeep HTML and HEAD opening tags
keep_spaces_between_attributesfalseKeep spaces between attributes
keep_commentsfalseKeep HTML comments
minify_csstrueMinify CSS in <style> tags and style attributes
minify_jstrueMinify JavaScript in <script> tags
remove_bangsfalseRemove bangs (e.g., <!--[if IE]>)
remove_processing_instructionsfalseRemove processing instructions (e.g., <?xml?>)
onError (function, optional)

Custom error handler for minification errors. By default, errors are logged to console.error and the original HTML is sent.

app.use(htmlMinifier({
  onError: (error) => {
    console.log('Minification failed:', error.message);
    // Custom error handling logic
  }
}));

Environment Variables

NODE_ENV

When NODE_ENV=production, minification is automatically enabled.

NODE_ENV=production node app.js

MINIFY_HTML

Explicitly enable minification in any environment:

MINIFY_HTML=true node app.js

Response Headers

When HTML is successfully minified, the middleware adds the following header:

X-HTML-Minified: true

This can be useful for debugging or monitoring.

Performance

Using the Rust-based @minify-html/node, this middleware offers:

  • Fast processing - Minification happens in native code
  • Low overhead - Minimal impact on response times
  • High compression - Typically 10-30% reduction in HTML size

Express-EJS-Layouts Compatibility

This middleware works perfectly with express-ejs-layouts:

const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const htmlMinifier = require('express-compress-html');

const app = express();

app.set('view engine', 'ejs');
app.use(expressLayouts);
app.use(htmlMinifier());  // Add after express-ejs-layouts

app.get('/', (req, res) => {
  res.render('index');
});

Error Handling

The middleware is designed to be fault-tolerant:

  • If minification fails, the original HTML is sent
  • Errors are logged but don't break the response
  • Custom error handlers can be provided via options

Examples

Basic Usage

const express = require('express');
const htmlMinifier = require('express-compress-html');

const app = express();
app.set('view engine', 'ejs');
app.use(htmlMinifier());

app.get('/', (req, res) => {
  res.render('home');
});

app.listen(3000);

Production Only

app.use(htmlMinifier({
  enabled: process.env.NODE_ENV === 'production'
}));

Keep Comments for Development

app.use(htmlMinifier({
  minifyOptions: {
    keep_comments: process.env.NODE_ENV !== 'production'
  }
}));

Custom Error Logging

app.use(htmlMinifier({
  onError: (error) => {
    logger.error('HTML minification failed', {
      message: error.message,
      stack: error.stack
    });
  }
}));

TypeScript Types

Full TypeScript definitions are included:

import htmlMinifier, { 
  MinifyOptions, 
  HtmlMinifierMiddlewareOptions 
} from 'express-compress-html';

const options: HtmlMinifierMiddlewareOptions = {
  enabled: true,
  minifyOptions: {
    minify_css: true,
    minify_js: true
  }
};

app.use(htmlMinifier(options));

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Credits

Built with @minify-html/node - the fastest HTML minifier available for Node.js.

Keywords

express

FAQs

Package last updated on 08 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts