express-compress-html
v1.0.1
Published
Fast HTML minification middleware for Express using Rust-based @minify-html/node
Maintainers
Readme
express-compress-html
⚡ Fast HTML minification middleware for Express using Rust-based @minify-html/node
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-htmlQuick 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:
| Option | Default | Description |
|--------|---------|-------------|
| do_not_minify_doctype | false | Don't minify DOCTYPE declarations |
| ensure_spec_compliant_unquoted_attribute_values | false | Ensure spec-compliant unquoted attribute values |
| keep_closing_tags | false | Keep closing tags (e.g., </div>, </span>) |
| keep_html_and_head_opening_tags | false | Keep HTML and HEAD opening tags |
| keep_spaces_between_attributes | false | Keep spaces between attributes |
| keep_comments | false | Keep HTML comments |
| minify_css | true | Minify CSS in <style> tags and style attributes |
| minify_js | true | Minify JavaScript in <script> tags |
| remove_bangs | false | Remove bangs (e.g., <!--[if IE]>) |
| remove_processing_instructions | false | Remove 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.jsMINIFY_HTML
Explicitly enable minification in any environment:
MINIFY_HTML=true node app.jsResponse Headers
When HTML is successfully minified, the middleware adds the following header:
X-HTML-Minified: trueThis 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.
