0
0
Expressframework~30 mins

HTTP caching headers (ETag, Cache-Control) in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
HTTP caching headers (ETag, Cache-Control) with Express
📖 Scenario: You are building a simple Express server that serves a JSON response. To improve performance and reduce unnecessary data transfer, you want to add HTTP caching headers: ETag and Cache-Control.This will help browsers cache the response and only request new data when it changes.
🎯 Goal: Create an Express server with one route /data that sends a JSON object. Add Cache-Control header to tell browsers to cache the response for 60 seconds. Add ETag header to allow conditional requests.
📋 What You'll Learn
Create an Express app with a route /data
Send a JSON response with a fixed object
Add a Cache-Control header with max-age 60 seconds
Add an ETag header based on the JSON content
Handle conditional requests using the If-None-Match header
💡 Why This Matters
🌍 Real World
HTTP caching headers help reduce bandwidth and speed up web apps by letting browsers reuse cached data when it hasn't changed.
💼 Career
Understanding and implementing caching headers is important for backend developers to optimize API performance and improve user experience.
Progress0 / 4 steps
1
Set up Express app and JSON data
Create an Express app by requiring express and calling express(). Create a constant called data with the exact JSON object { message: "Hello, world!", version: 1 }.
Express
Need a hint?

Use const to declare variables. The JSON object must have message and version keys with exact values.

2
Add Cache-Control header configuration
Create a constant called cacheDuration and set it to 60 to represent 60 seconds cache duration.
Express
Need a hint?

Use const cacheDuration = 60; to set the cache time in seconds.

3
Create /data route with Cache-Control and ETag headers
Add a GET route /data to the Express app. Inside the route handler, convert data to a JSON string called jsonData. Create an etag string by hashing jsonData using require('crypto').createHash('md5').update(jsonData).digest('hex'). Set the Cache-Control header to public, max-age=cacheDuration. Set the ETag header to the etag string. Check if the request header If-None-Match matches etag. If yes, respond with status 304 and end. Otherwise, send the JSON response with jsonData.
Express
Need a hint?

Use app.get to create the route. Use res.set to add headers. Use req.headers['if-none-match'] to check the ETag sent by the client.

4
Start the Express server
Add code to start the Express server listening on port 3000. Use app.listen(3000).
Express
Need a hint?

Use app.listen(3000) to start the server on port 3000.