Compression
The npm compression package is a middleware that can compress response bodies for requests that traverse through it. This helps reduce the size of data that's sent over the network, leading to quicker response times and lower bandwidth usage. It uses the zlib library to perform gzip or deflate compression, both of which are widely supported by modern web browsers.
For more information about the npm compression package, please visit the npm compression package.
Benefits
-
Performance: It can significantly reduce the size of the response body, thereby decreasing the time it takes for a client to download the response and render the content.
-
Efficiency: It helps in reducing bandwidth consumption which is especially useful if your server is sending large amounts of data or if you have limited bandwidth.
-
Overhead: While compression reduces the size of the response body, it does add some computational overhead on the server-side as the server must compress the response body before sending it.
This might not be ideal for high traffic websites where server resources are at a premium.
Not all content benefits from compression. Binary files like images and videos are already compressed and trying to compress them further can sometimes increase their size.
When to use
Deciding on when to use compression depends on the use case. If your website serves a lot of textual data (HTML, CSS, JS, JSON, XML etc.), then using the npm compression package can result in significant bandwidth savings and performance benefits. However, if your website is extremely high traffic, the additional computational overhead of compression might start to become a bottleneck.
In high traffic scenarios, it might be more beneficial to use a reverse proxy or a CDN (Content Delivery Network) which can serve static assets and perform caching. This can offload some of the traffic from your main servers and also serve content from locations geographically closer to users, resulting in faster response times. These services usually handle compression themselves, meaning you wouldn't need to use the npm compression package.
Modern approaches could involve a combination of techniques - serving static assets from a CDN, caching responses where appropriate, utilizing HTTP/2 for multiplexing, and splitting up your application into microservices to distribute the load.
Remember, these approaches aren't mutually exclusive. Often the best approach is to use a combination of these techniques based on the specific requirements of your application. Testing and monitoring your application under realistic workloads can help you make the best decision.
Install
Install the npm compression middleware.
npm i compression && npm i -D @types/compression
Setup
Add the compression middleware to your application using the out-of-the-box ExpressoTS middleware system.
@provide(App)
export class App extends AppExpress {
private middleware: IMiddleware;
private provider: IProvider;
constructor() {
super();
this.middleware = container.get<IMiddleware>(Middleware);
this.provider = container.get<IProvider>(Provider);
}
protected configureServices(): void {
this.middleware.addCompression();
}
}
If middleware is not added to the application, ExpressoTS will emit a warning message.
WARN [resolver] Middleware [compression] not installed. Please install it using your package manager.
Usage example
Once the middleware is added to the application, it will compress all responses that pass through it. The middleware can be configured with various options to control the behavior of compression.
Also you can add the compression middleware globally or to a specific route.
Using compress with filters, filtering requests that contain payload bodies larger than 100 * 1024 bytes:
export class App extends AppExpress {
private middleware: IMiddleware;
private provider: ProviderManager;
constructor() {
super();
this.middleware = container.get<IMiddleware>(Middleware);
this.provider = container.get(ProviderManager);
}
protected configureServices(): void | Promise<void> {
this.middleware.addCompression({
level: 6,
threshold: 100 * 1024,
filter: (req, res) => {
if (req.headers["x-no-compression"]) {
return false;
}
return compression.filter(req, res);
},
});
}
}
Add to a specific route
Adding the compression middleware to a specific route is also possible via the ExpressoTS middleware system.
export class App extends AppExpress {
private middleware: IMiddleware;
private provider: ProviderManager;
constructor() {
super();
this.middleware = container.get<IMiddleware>(Middleware);
this.provider = container.get(ProviderManager);
}
protected configureServices(): void | Promise<void> {
this.middleware.addMiddleware({
path: "/api",
middlewares: [
compression({
level: 6,
threshold: 100 * 1024,
filter: (req, res) => {
if (req.headers["x-no-compression"]) {
return false;
}
return compression.filter(req, res);
},
}),
],
});
}
}
Add in the controller
Adding the middleware in the controller applies the compression middleware to all routes in the controller.
@controller("/", compression())
export class AppController {
@Get("/")
execute(): string {
return "Hello from Expressots!";
}
}
Add in the method
Adding the compression middleware in the method applies the compression middleware to the specific route.
@Get("/", compression())
execute(){};
Support us ❤️
ExpressoTS is an MIT-licensed open source project. It's an independent project with ongoing development made possible thanks to your support. If you'd like to help, please read our support guide.