What is koa-etag?
The koa-etag package is a middleware for Koa that automatically handles ETag (Entity Tag) headers for HTTP responses. ETags are used for web cache validation and conditional requests, helping to reduce bandwidth and improve web application performance.
What are koa-etag's main functionalities?
Automatic ETag Generation
This feature automatically generates ETag headers for HTTP responses. The middleware calculates the ETag based on the response body and sets the appropriate header.
const Koa = require('koa');
const etag = require('koa-etag');
const app = new Koa();
app.use(etag());
app.use(async (ctx) => {
ctx.body = 'Hello World';
});
app.listen(3000);
Conditional GET Requests
This feature works in conjunction with the koa-conditional-get middleware to handle conditional GET requests. If the ETag matches the client's cached version, a 304 Not Modified response is sent, saving bandwidth.
const Koa = require('koa');
const etag = require('koa-etag');
const conditional = require('koa-conditional-get');
const app = new Koa();
app.use(conditional());
app.use(etag());
app.use(async (ctx) => {
ctx.body = 'Hello World';
});
app.listen(3000);
Other packages similar to koa-etag
etag
The etag package is a standalone utility for generating ETag HTTP headers. Unlike koa-etag, it is not specific to Koa and can be used with any Node.js HTTP server. It provides more granular control over ETag generation but requires manual integration.
koa-conditional-get
The koa-conditional-get package is a middleware for Koa that handles conditional GET requests using If-None-Match and If-Modified-Since headers. While it does not generate ETags itself, it works well in combination with koa-etag to provide a complete caching solution.
koa-static
The koa-static package serves static files and includes built-in support for ETag headers. It is more specialized for serving static assets, whereas koa-etag is more general-purpose and can be used with any type of response.
koa-etag
ETag support for Koa responses.
Installation
$ npm install koa-etag
Example
var etag = require('koa-etag');
var koa = require('koa');
var app = koa();
app.use(etag());
app.use(function(next){
return function *(){
yield next;
this.body = 'Hello World';
}
})
app.listen(3000);
console.log('listening on port 3000');
License
MIT