Unread Notifications

Latest Notifications

No Notifications

You're all set! Start a discussion by leaving a comment on a lesson or replying to an existing comment.

AdonisJS Quick Tip

Minify Your AdonisJS HTML in 5 Minutes

06:23 Watch
1:03 Read

We'll learn how we can alter all our AdonisJS HTML response bodies using a simple global middleware to add HTML minification.

Watch on YouTube

🔗 HTML Minifier Package: https://github.com/kangax/html-minifier

🕑 Chapters
00:00 - What's The Default Behavior
00:40 - Install HTML Minifier
01:10 - How To Alter Response Body
01:35 - HTML Minfier Middleware
02:50 - Inspecting What It's Doing
03:30 - Limiting Middleware Execution
04:56 - Testing Our HTML Minification Middleware
05:40 - Outro

1. Install HTML Minifier Package

npm i html-minifier

2. Create HTML Minfier Middleware

node ace make:middleware HtmlMinifier

2. Register Global Middleware

// start/kernel.ts

  () => import('@ioc:Adonis/Core/BodyParser'),
  () => import('App/Middleware/HtmlMinifier')

3. HTML Minifier Middleware

import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
const minify = require('html-minifier').minify

export default class HtmlMinifier {
  public async handle({ request, response }: HttpContextContract, next: () => Promise<void>) {
    // BEFORE NEXT: altering, authorizing, preparing request
    await next()
    // AFTER NEXT: altering response
    const method = request.method()
    const accepts = request.accepts([]) ?? [] as string[]
    const isXml = request.url().endsWith('.xml')

    // if not GET request or doesn't expect HTML or is XML, then exit
    // since await next() already ran, we're safe to just return here to exit
    if (method !== 'GET' || !accepts.includes('text/html') || isXml) {

    // get the minified HTML of our current response body
    const minifiedBody = minify(response.getBody(), {
      minifyCss: true,
      minifyJs: true,
      removeComments: true,
      collapseWhitespace: true

    // set minfied HTML as new response body


Prepared By

Tom Gobich

Burlington, KY

Owner of Adocasts, JavaScript developer, educator, PlayStation gamer, burrito eater.

Visit Website