Astro: How to Set Up More Powerful HTML Minification (in 31 Seconds)
Published on Mar 17, 2026 (updated Nov 3, 2026), filed under development, html, performance, optimization. (Share this post, e.g., on Mastodon.)
This post originally used HTML Minifier Next. It was updated when HTML Minifier Next merged with and continued as HTML Minifier.
You’re running an Astro site—and want to speed it up and minify your HTML (and inline CSS, JS, and SVG)?
HTML Minifier gets you more effective results than the setup Astro ships with (at least when testing against Astro 6.0.4).
It takes just two steps to set up HTML Minifier, which you can customize further afterwards:
1. Install
Install HTML Minifier in your project (as a dev dependency):
npm i -D html-minifier2. Configure
Add the following to your Astro configuration (astro.config.js or similar):
// Close to other imports:
import { readFileSync, writeFileSync, readdirSync } from 'fs';
import { join } from 'path';
import { fileURLToPath } from 'url';
import { minify } from 'html-minifier';
// Before `defineConfig`:
function htmlMinifier() {
return {
name: 'html-minifier',
hooks: {
'astro:build:done': async ({ dir }) => {
const distDir = fileURLToPath(dir);
const files = readdirSync(distDir, { recursive: true, encoding: 'utf-8' })
.filter(f => f.endsWith('.html'))
.map(f => join(distDir, f));
for (const file of files) {
const minified = await minify(readFileSync(file, 'utf-8'), {
preset: 'comprehensive'
// Options: https://github.com/j9t/html-minifier?tab=readme-ov-file#options-quick-reference
});
writeFileSync(file, minified);
}
}
}
};
}
// In `defineConfig` block:
integrations: [htmlMinifier()],And that’s it.
The configuration uses HTML Minifier’s “comprehensive” preset for a pretty competitive result, but you can switch to the “conservative” preset or fully customize minification.
Then, does this take 31 seconds? Contrary to me timing this with Eleventy, I don’t know—this time, I’m just making up the number 😉
Jonas Geiler provides a wrapper with astro-html-minifier-next [built on HTML Minifier Next, which HTML Minifier now continues]. I didn’t try it—I wanted to develop a better feeling for Astro and for setting up HTML Minifier in an Astro project—, but maybe you like that solution, too!
About Me
I’m Jens (long: Jens Oliver Meiert), and I’m an engineering lead, guerrilla philosopher, and indie publisher. I’ve worked as a technical lead and manager at various companies (e.g., Google); I’m an active web and tool developer (code optimization, digital defense), a contributor to web standards (like HTML, CSS, WCAG), and a book author (O’Reilly, dxsrc). You’ll like my work if you value principled, pragmatic problem-solving. Let’s connect.
