Middleware
compression & Etag
1. Gzip Compression
Theory: Compression reduces the size of the HTTP response body before it is sent to the client. Since text-based files (HTML, CSS, JS, JSON) have significant repetitive patterns, they can often be compressed by 70% to 90%.
The Process: When a client sends a request, it includes an
Accept-Encoding: gzipheader. The server compresses the data, sends it, and the browser decompresses it instantly upon arrival.Implementation: The
compressionmiddleware is the standard tool for this in Express
const compression = require('compression');
const express = require('express');
const app = express();
// Use compression middleware for all responses
app.use(compression());Optimizing the performance of an Express application involves reducing the amount of data transferred and ensuring that the client doesn't download the same file twice. Compression and ETags are the two primary mechanisms for achieving this at the HTTP level.
Performance Note: Compression uses server CPU. While usually worth the trade-off for text, you should avoid compressing already-compressed formats like JPEGs or PDFs, as this can actually increase the file size and waste CPU cycles.
2. ETags (Entity Tags)
Theory: An ETag is a unique identifier (usually a hash) assigned to a specific version of a resource. It is part of the HTTP Cache Validation process.
The Goal: To prevent the server from sending a full response if the file hasn't changed since the client last downloaded it.
The Lifecycle:
First Request: Server sends the resource + an
ETagheader (e.g.,ETag: "v1").Second Request: Client sends the request with
If-None-Match: "v1".Validation: The server checks if the resource still matches "v1".
Efficiency: If it matches, the server sends a 304 Not Modified status with an empty body. The browser then loads the file from its local cache.
3. Express ETag Configuration
Express enables ETags by default using a "weak" hashing algorithm. You can customize this behavior based on your performance needs.
// Disable ETags (not recommended for production)
app.set('etag', false);
// Use strong ETags (guarantees byte-for-byte identity)
app.set('etag', 'strong');