Minify Your AdonisJS HTML in 5 Minutes

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

Published
Dec 11, 22
Duration
6m 23s

Developer, dog lover, and burrito eater. Currently teaching AdonisJS, a fully featured NodeJS framework, and running Adocasts where I post new lessons weekly. Professionally, I work with JavaScript, .Net C#, and SQL Server.

Adocasts

Burlington, KY

🔗 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
Copied!

2. Create HTML Minfier Middleware

node ace make:middleware HtmlMinifier
Copied!

2. Register Global Middleware

Server.middleware.register([
  () => import('@ioc:Adonis/Core/BodyParser'),
  () => import('App/Middleware/HtmlMinifier')
])
Copied!
  • start
  • kernel.ts

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) {
      return 
    }

    // 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
    response.send(minifiedBody)
  }
}
Copied!

Join The Discussion! (0 Comments)

Please sign in or sign up for free to join in on the dicussion.

robot comment bubble

Be the first to Comment!

Playing Next Lesson In
seconds