Introduction to ETag
ETag, or “Entity Tag”, is an HTTP header used for web cache validation and conditional requests from browsers for resources. It aids in reducing bandwidth and improving performance by validating resources only when they are updated.
Getting Started
The ETag header allows a client to make conditional requests and update resources only when necessary
Basic ETag Example
GET /index.html HTTP/1.1 Host: www.example.com If-None-Match: "686897696a7c876b7e"
Responding to ETag
HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1024 ETag: "686897696a7c876b7e"
Using ETag with Express.js
Here are some examples of how to use ETag with the popular JavaScript framework, Express.js.
const express = require('express'); const app = express(); app.use((req, res, next) => { const etag = generateETag(someResource); res.setHeader('ETag', etag); if (req.headers['if-none-match'] === etag) { res.sendStatus(304); // Not Modified } else { next(); } }); function generateETag(resource) { // Generate ETag based on resource (could use a hash function) return '"' + resource.length + '-' + Date.now() + '"'; } app.get('/resource', (req, res) => { const resourceData = 'Some data that may change'; res.send(resourceData); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
ETag in Flask (Python)
from flask import Flask, request, make_response app = Flask(__name__) @app.route('/resource') def resource(): resource_data = 'Some data that may change' etag = generate_etag(resource_data) if request.headers.get('If-None-Match') == etag: return '', 304 response = make_response(resource_data) response.headers['ETag'] = etag return response def generate_etag(data): # Generate ETag based on data return str(hash(data)) if __name__ == '__main__': app.run(port=5000)
App Example
Here is a simple example demonstrating the use of ETag in a small app. This app serves a resource that frequently updates, and ETag helps manage caching efficiently.
// index.html <!DOCTYPE html> <html> <head> <title>ETag Example</title> </head> <body> <div>Resource Data: <span id="data"></span></div> <script> fetch('/resource') .then(response => { if (response.status === 304) { document.getElementById('data').innerText = 'Not Modified'; } else { return response.text().then(data => { document.getElementById('data').innerText = data; }); } }); </script> </body> </html>
Conclusion
ETag is a powerful tool for web optimization. By understanding and implementing it, developers can greatly improve the efficiency and performance of their web applications.
Hash: fcaec3a55087c997f24ba2a70383ed9b7607fd85f0ae2e0dccb5ec094c75f009